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

What's up with the Chrome Dev Tools Error Log?

I am having an issue with debugging JavaScript files using breakpoints in Chrome Dev Tools. Whenever an error occurs, a red error message flashes on the screen so quickly that I can't read what it says. Is there a way to change this setting or access ...

Removing single quotes and replacing them with spaces when passing data from JavaScript to MySQL

I'm currently focused on JavaScript using Hapi.js in my role at the company. My main task involves retrieving data from MongoDB and transferring it to a MySQL database. The challenge arises when dealing with data that contains single quotes within th ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

The issue arises in React when input elements fail to render correctly following a change in value, specifically when the keys remain identical

Click here to view the code sandbox showcasing the issue The code sandbox demonstrates two versions - a working one where Math.random() is used as the key, and a not working one where the index of the array is used as the key. When the array this.state.v ...

Capturing groups with Python regex

I have a sentence similar to the following: sentence = "2020 Lorem - Ipsum Ipsum Ipsum Ipsum-Ipsum Ipsum" I am trying to extract capture groups as follows: (2020) (Lorem) - (Ipsum) (Ipsum Ipsum Ipsum-Ipsum Ipsum) I attempted to achieve this using t ...

Adjust the stacking order of bars in a vertical chart and exclude negative values with Vega-Lite

I am utilizing this chart as a guide for my current project Explore Vega Editor here Is there a way to rearrange the order of the 'Measure' while keeping 'Measure 1' at the top, disregarding its negative value? I want to display the & ...

Enhance the functionality of your Rails application by implementing Ajax or jQuery to asynchronously load table elements separately from the page

Currently, I am facing an issue with a page that displays a list of user sites. The problem lies in the fact that I am making an API call for each site to check its status, which is causing the page to load very slowly. To address this issue, I would like ...

Struggling to align the image elements accurately

I am aiming to create a layout similar to the image displayed below.https://i.sstatic.net/Q5n8J.png To be more specific, my goal is to scatter smiley faces randomly within a 500px area while also having a border on the right side of the area. However, wi ...

What are the steps to integrate mailjet into my Vue application?

I am looking to utilize mailjet for my contact form. I have installed it using "$ yarn add node-mailjet" and followed the steps provided. However, I am a bit confused about whether I am integrating mailjet correctly. Below is the code I am currently using: ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

Displaying an iframe on an AR marker with the help of CSS3DRenderer and jsartoolkit

I am trying to achieve an interesting effect by overlaying a html iframe on top of an augmented reality marker. However, I seem to be facing some issues with the CSS3DRenderer not producing the same result as the WebGLRenderer and I'm struggling to pi ...

Leverage AngularJS to effectively parse JSON data using scope variables

I am trying to JSON parsing in AngularJS using $stateParams in the controller below: rerunApp.controller('rerunCategoryListCtrl', function($scope, $http, $stateParams) { var stpNameCat = $stateParams.nameCat; $http.get(JSON UR ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

Checking a String for a Specific Pattern in Angular 6 using Regular Expressions

urn:epc:id:sgln:345344423.1345.143 I need to verify if the string above, entered into a text box, matches the specified format consisting of (urn:epc:id:sgln) followed by numbers separated by two dots. ...

JavaScript Flash player for iPad

As many of us know, the iPad does not support Flash. However, I am curious if the iPad sends any specific error messages that can be captured using Javascript. I realize one method is to detect the iPad from the user agent string, but I am interested in w ...

Jquery UI slider malfunctioning would require troubleshooting

I am currently working on implementing slider functionality with jQuery. The slider is visible and functioning properly in terms of taking in values, however, the values are not displayed on the screen as expected. I have used console.log to track the ui.v ...

Drop the <span> element into a paragraph by utilizing JQuery's drag and drop feature

Trying to drag and drop <span> into <p>. The code is functional, but encountering 3 issues: When editing content inside <p> by typing (e.g. three words) and then dragging <span> into <p>, the newly typed words are consider ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...

Repetitive use of multiple submit buttons in AngularJS

i'm currently working with AngularJS Currently facing this issue: view screenshot I have utilized the following HTML code to display submit button for two different types of forms. One for TEXT Form and one for ENUM Form: <div ng-controller="g ...