Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings.

For example:

foo I have four toys bar    //single line

foo     //multiline
I
have
four
toys
bar

foo I have three pets bar

foo
I
have
three
pets bar

How can I extract the text between "foo" and "bar" that contains the word "four"?

Desired output:

I have four toys

I
have
four
toys

Here is my current regex code:

foo[\s\S]*?(four)[\s\S]*?bar

While this code works, it selects all text until the word "four" even if it's not within the "foo" and "bar" boundaries

foo I have three pets bar

foo I have four toys bar

foo
I
have
three
pets bar

My goal is to only extract text between "foo" and "bar" when it includes the word "four"

Answer №1

Here is a helpful regex pattern that can be used in dot all mode:

\bhello\s+(?:(?!\bworld\b).)*?\s+goodbye\s+(?:(?!\bhello\b).)*?\s+world

var input = `hello I have goodbye options world

hello
I
have
goodbye
options
world

hello I have no goodbye idea world

hello
I
have
no
goodbye
idea world`;

var matches = input.match(/\bhello\s+(?:(?!\bworld\b).)*?\s+goodbye\s+(?:(?!\bhello\b).)*?\s+world/gs)
                   .map(x => x.replace(/^hello\s+|\s+world$/g, ""));
console.log(matches);

An explanation of this elaborate regex pattern could be beneficial:

\bhello\s+          match 'hello' followed by one or more whitespace characters
(?:(?!\bworld\b).)*?  match any content WITHOUT encountering 'world'
\s+goodbye\s+        match 'goodbye' surrounded by whitespace
(?:(?!\bhello\b).)*?  match any content WITHOUT encountering 'hello'
\s+world            whitespace followed by ending 'world'

It's important to note that the match() method requires a map step to remove leading hello and trailing world from each match.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am utilizing Vuex to store all of the product details and handle API request queries efficiently

Question regarding Vue/Vuex efficiency and best practices. I am working with an API that returns a paginated data-set of 50 products, which I am storing in a Vuex store. When displaying all products, I iterate over the Vuex store. Now, for individual pr ...

Quantifying the passage of time for data entry

Looking to create a quiz form where I can track how long it takes users to input/select answers. I attempted the following code but the timing seems off: $('input, select').on('focus', function(event) { el = $(this); name ...

Data binding in Vue.js seems to be malfunctioning

I'm having trouble with my Vue component creation. I've been using v-show to hide certain elements, but it doesn't seem to be working as intended. The goal is to hide an element when clicked from a list by setting element.visible to false i ...

Tips for utilizing vulnerable web scripts on SSL-enabled pages

After implementing SSL to secure my pages, I encountered an issue where one of my scripts no longer functions properly. Specifically, I had a script on my page that was used to display the visit count from this website. Previously, it was functioning fla ...

Exploring Nested Views in a MEAN Application using UI Router

I am currently developing a MEAN application and struggling to get my ui-router functioning correctly. Within my index.html template, I have loaded all the necessary javascript and css for my application such as angular, jquery, angular-ui-x, bootstrap. I ...

What is the best way to dynamically update a specific value within an object based on the current state in React/Next?

I have implemented a Context API where an object is set, and when the user clicks, the state changes. I need to update a specific value with the new state value. const initialState = { notification: false, setting: false, profile: false, } exp ...

Optimizing the JSON date structure

After receiving a datetime value in JSON with the format: Created "/Date(1335232596000)/" I developed a JavaScript function to display this value on the front end. Here's the code snippet: return new Date(parseInt(date.substr(6))); However, the c ...

Having issues with showing an image from a specified component in a separate file

I am facing an issue where my image is not displaying in the app.js file, even though I have imported it from another file named comp.js. Here is the current code in app.js: import React from 'react'; import TextImg from "./Comp"; impor ...

Retrieve the values and IDs for every span element within the form

I have been attempting to retrieve all span elements within a form and make them editable input text fields. Once you click away, they should revert back to span elements. I will provide a live example in the attached fiddle. I tried my hand at it, but the ...

Is it possible to invoke the created() function in Vue from another method?

Currently, I am developing an application in Vue. Upon loading the page, a cookie containing the user's zip code is retrieved and used to perform a search. However, users should also have the ability to change their zip code if it is incorrect. I woul ...

I'm a beginner when it comes to Android WebView and incorporating JavaScript into my projects

Struggling to make my Android app work with JavaScript, even though I've enabled it. Despite all the research I've done suggesting it should work, it's not. Any assistance would be greatly appreciated. Below is my Java code: protected ...

Encountering a problem while trying to launch the development server for a React application using the npm-start

I followed the steps to create a react application using npx create-react-app myapp, but when I use npm start, it fails to start a developer server. Even after trying to reinstall the node_modules, the issue persists. I am using the latest versions of Reac ...

Performing an HTTP request response in JavaScript

I am trying to make an HTTP request that returns the data in JSON format using 'JSON.stringify(data)'. var xhr = new XMLHttpRequest(); xhr.open("GET", "/api/hello", true); xhr.send(); xhr.onreadystatechange = function () { console.log(xhr.r ...

When the user clicks on the iframe, they will be redirected to the

My goal is to create a scenario where clicking on an iframe opens the same URL in a new browser tab, while ensuring that scroll and other mouse events within the iframe are not affected. I have experimented with various approaches but none have been succe ...

When using v-for to render an array list fetched from AsyncData, an error is thrown: The virtual DOM tree rendered on the client-side does not match the one

For my application, I am utilizing Nuxt.js. On one of the pages, I am using AsyncData to fetch an array of data objects from my API asynchronously. These data objects are then rendered in my template using v-for. Everything is functioning properly until I ...

A guide on removing an element from a state array in a React functional component for a To-Do List application

I need help making a to-do list item disappear when clicked. The deleteHandler method is not working as expected. Can anyone provide logic on how to filter out the clicked item? import React, { useState } from 'react'; const ToDoList = () => ...

Issues arise when trying to integrate external JavaScript files into a Vue application

I am facing an issue with including external JS files in my HTML document. The website requires these files to function properly. What I have attempted: In the main.js file, I tried adding these imports: import '../../assets/js/jquery-3.5.1.min&apos ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

Ajax Multidimensional Array Response

Currently, I am attempting to retrieve a Multiarray response from an ajax Post JSON request. After numerous attempts, I am hopeful that I can get assistance here... JS AJAX RESPONSE var data = { "myid": "1234" }; $(".the-return").html(""); $.ajax({ ...

Conceal any ng-repeat elements that do not contain corresponding grandchildren within two levels of nested ng-repeats

Apologies for the enigmatic title, but the issue at hand is quite cryptic ¯\_(ツ)_/¯ I'm dealing with a complex problem involving 3 nested ng-repeats to display Google Analytics' account structure. Within this structure are multiple acco ...