Searching for text within paragraphs using Regex

I am attempting to find the paragraph that contains a specific keyword.

Here is an example text:

In my text file, there are multiple paragraphs with varying lengths.

Each paragraph may be on multiple lines.

There is always a newline between each paragraph. I want to locate a paragraph that contains the desired keyword and match this line as well.

I don't need to match the first or last paragraphs (let's assume each paragraph has newlines around it).

Keyword: desired (so the middle paragraph should match).

I have tried using this regex pattern:

var regX = /(.+\r?\n)+.*desired.*(?=(\r?\n)?)/igm;

This pattern currently matches the first two lines but not the last one:

There is always a newline between each paragraph. I want to locate a paragraph that contains the desired keyword.

Changing .*desired.* to .*desired[\s\S]* selects too much (it picks up the 2nd and 3rd paragraphs in the example) (.*desired[\s\S]*? doesn't work either - not reluctant enough.)

Thank you for your assistance.

Answer №1

Check it out:

^\n(?:.+\n)*.*\bcontains\b.*\n(?:.+\n)*(?=\n)

Remember to use /gm. Take a look at the example.

Keep in mind that this regex may lead to catastrophic backtracking, but unfortunately, there aren't many solutions for it in JavaScript.

This expression essentially matches an empty line, followed by some lines ((?:.+\n)*), then by a line containing contains (.*\bcontains\b.*\n), and once again by 0 or more lines ((?:.+\n)*), ensuring that the final newline is immediately followed by another newline: (?=\n).

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

The loop outcome is not determined

Storing function arguments in a specific format ["2015-07-05 00:30", 59] ... ["2015-07-05 01:00", 62] function generateCSV(timeAndValue) { object = {} var zero = 0; for(i = 0; i < timeAndValue.length; i++){ var value = timeAndVa ...

I'm facing issues with Webpack not being able to resolve and locate the node

Encountering difficulties while setting up and running the Three.js library as a module based on the guidelines provided in the manual at Here is a summary of the steps taken: Created package.json npm init Installed webpack npm i --save-dev webpack we ...

Unable to transmit props through components with Vue router

Hey there, I'm currently facing an issue with passing props from my vue router. It seems like nothing is being printed and when I checked in the mounted hook, it's returning undefined. However, strangely enough, when I use console.log(this.$route ...

There seems to be a glitch preventing the Redis client from properly executing

Having some trouble with my Redis implementation in Node.js. Despite using async/await as recommended in the docs, I'm only seeing 'console log 1' being logged. Any ideas on what might be causing this issue? Any help or suggestions would be ...

Unable to retrieve location data within the function

I've been grappling with this issue for quite some time now. I have three functions that are all functioning properly individually. However, I'm facing a challenge of retrieving the value from getUserCoordinates() and passing it to fetchCurrentTe ...

What could be causing the mousewheel event in my code to remain active?

Whenever I try to scroll on Google Chrome, an error occurs on my website. jquery-3.3.1.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See To resolve this issue: $(document).ready(f ...

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Navigating with React Router Dom and parsing objects in search parameters

Currently, I am utilizing React Router Dom v6 and require the ability to retain object search parameters within the URL. My current approach involves: const [searchParams, setSearchParams] = useSearchParams(); const allSearchParams = useMemo(() => { ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

Sorting a targeted section of an already organized 2D Array based on updated values, solely if the initial sorted values align in Javascript

A challenging scenario I need help with involves an array containing objects, each with a score and a rank as shown below: [ { "score": 20, "rank": 12 }, { "score": 20, "rank": 7 }, { "score": 34, "rank": 4 } ] To begin w ...

Error: Unable to assign value to the innerHTML property of an undefined element created by JavaScript

When designing my html form, I encountered an issue where I needed to display a message beneath blank fields when users did not fill them out. Initially, I used empty spans in the html code to hold potential error messages, which worked well. However, I de ...

Altering various HTML components with every swipe of SwiperJS

I am new to working with JavaScript and I have integrated a Swiper JS element into my HTML page. Here is the current code I am using: <head> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css&quo ...

Unveiling the approach to accessing a nested function with jQuery

While the title may be a bit misleading, I couldn't think of a better way to describe it. I've created a function that allows a small pop-up window to appear when a link is clicked (to confirm whether or not an article should be deleted). Addit ...

Having trouble with JQuery Tooltip content not being overridden as expected

Hey, I'm having an issue with the tooltip in my code snippet on JSFiddle. The text specified in JQuery's tooltip content option is not replacing the tooltip as expected. Can someone help me figure out what I might be doing wrong or missing? Than ...

Evaluating different attributes within a single entity

I was attempting to write some code that checks if two individuals share the same birthday. Person "a" and person "b" do not have the same birthday, yet the console output shows: a was born on day 1 a has the same birthday as a a has the same birthday as ...

Having difficulty changing the value of a Select element in AngularJS

Struggling to update the select value from AngularJs. Check out my code below: <select ng-model="family.grade" > <option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option> </s ...

What causes a Next.js App to crash when a prop is not defined in destructuring code?

Let me share the issue I am facing. I have developed a custom Context API wrapper to handle all my data. However, there is this docType property that may not always be defined or may not exist at times. When I destructure it in this way: const { docType } ...

Using a Vue component to send a form for submitting data into the backend database of a Django application

Where should the connection between a form within a Vue component and a Django backend be established? In my frontend, I am utilizing VueJS where my primary component can retrieve data from a JSON file through an API specified in my Django view and URL fi ...

The event handler on line 72 triggered an error that was not handled, resulting in an error message indicating a permission issue on OpenShift: "Error: cannot listen for connections

I have been working on creating a basic chat app. Initially, it was running smoothly on localhost:3000/chat.html. However, upon deployment on OpenShift, I encountered a crash accompanied by the following error message (as seen after running rhc tail): UPD ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...