Obtain a multiline match using regular expressions

Is there a way to use regex to match only multi-line strings without matching single-line strings as well? Here is the current regex I am using:

Regex

('|"|`)[\s\S]*?(\1)

Test string

"not a match"
"need
to
match"

https://regex101.com/r/DXahXG/1

Answer №1

Your input string includes three possible substrings enclosed in double quotes:

  • "not a match"
  • "\n"
  • "need\nto\nmatch"

Due to the risk of the regex engine picking up the ending " of one pair as the beginning " of the next pair, using lookarounds may not be reliable. The regex

(['"`])(?:(?!\1).)*\n[\s\S]*?\1
demonstrates this issue in an example.

To mitigate this problem, it is recommended to apply your regex and then filter out matches containing newline characters:

const text = '"not a match"\n"need\nto\nmatch"';
const rx = /(['"`]).*?\1/gs;
console.log( text.match(rx).filter(x => x.includes('\n')) )

Answer №2

A multiline string is a string that has a minimum of one newline character. An example pattern to match this type of string would be:

('|"|`)[\s\S]*?\n[\s\S]*(\1)

However, using this pattern will match the entire example provided, as [\s\S]* includes the string delimiters.

To better handle this situation, you can try using the following pattern:

'[^']*?\n[^']*?'|"[^']*?\n[^']*?"|`[^']*?\n[^']*?`

This revised pattern takes into account escaped quotation marks, which the previous pattern did not address.

Answer №3

Perhaps this seems overly complicated?

('|"|`)(?:(?:(?!\1).)+?\n)+(?:(?!\1).)+\1

Let's break it down:

                ┌─ matches at least one of the specified characters
                │                ┌─ followed by one or more non-quote characters
                │                │  and ending with a quote character
('|"|`)(?:(?:(?!\1).)+?\n)+(?:(?!\1).)+\1
└──┬──┘   │  │    ││     │
   └────────────────────────────── matches the opening specified character 
          │  │    ││     │       and groups it in group 1
          │  │    ││     │
          │  └──┬─┘└─────│────── matches any character that is not a specified character
          │     └───────│──────── ensures the fewest possible matches
          └────┬───────┘
               └──────── follows with a line break

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

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

How can I utilize passed in parameters in Meteor React?

I am trying to figure out how to use two params that I have passed in the following example. Can someone please assist me? updater(layer, item){ this.setState({layer5: <img id="layer5" className="on-top img-responsive center-block" name="layer5" ...

Having trouble uploading an image using the Cloudinary API in a Next.js project

I am currently working on a page meant for creating posts. Initially, the page was designed to handle multiple image uploads. However, I made some adjustments so that it can now accept only a single image upload. Unfortunately, after this modification, the ...

Adjust the position of an image to move it closer to the top using CSS

I have a fiddle where I am trying to adjust the position of an image (keyboard) to match a specific design. https://i.sstatic.net/flqCH.png In my fiddle, the keyboard image is slightly lower than the desired position shown in the design. I am looking for ...

Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format. I am looking to convert these price values into strings within the same object My approach involves using the map function: var prods = [ { "id": "id-1", "price": 239000, "inf ...

Display Checkbox Selections in a Popup Message Box

I've run into a problem while working on an assignment. My goal is to show the checkbox values for toppings in the alert box popup upon submission. However, only the text box and radio values are displaying, while the checkbox returns as blank. Any ...

Go through each .md document, transform them into HTML format, and dispatch them

I am using fs to read files in .md format and transform them into HTML files. Here is the code snippet I have written: fs = require('fs'); fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (err, data) { i ...

What could be the reason why the toggleClass function is not being run

I've been running into a little issue with using the .toggleClass function in my code. It seems to work inconsistently, and despite reading various posts on the topic, I haven't found a solution that works for me. Could you provide some assistan ...

Ways to specify the default value for a component

A sample of my custom component code (Amount.tsx) is shown below: const Price = ({ price, prevPrice }) => { return ( <div className="product-amount"> <div className="price"> {prevPrice ? (<del class ...

Struggling to populate dropdown with values from array of objects

My issue is related to displaying mock data in a dropdown using the SUIR dropdown component. mock.onGet("/slotIds").reply(200, { data: { slotIds: [{ id: 1 }, { id: 2 }, { id: 3 }] } }); I'm fetching and updating state with the data: const ...

Showing Div content from AngularJS response

Query -- I am currently using a Controller in AngularJs that performs an $http.get request and receives data as a response. The data includes an HTML DivID and corresponding classes. How can I extract this DivID from the response and transfer it to the vi ...

Error: Firebase is not recognized as a valid function

I have been attempting to go through the firebase Node tutorial at this URL: Running my node.js app leads to a crash with a "TypeError: Firebase is not a function" error. Here is an excerpt from my index.js file: var Firebase = require("firebase"); var f ...

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

Trigger a JavaScript function upon clicking a link

Is it possible to have a CMS that loads articles using ajax, where the article is loaded through a function with parameters, and when a certain link is clicked, it redirects to the target page and launches the function on that page? For instance, let' ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

What is the process for importing from vueuse into Vue SFC Playground?

After attempting to integrate vueuse through an Import Map using the code @vueuse/core": "https://www.unpkg.com/@vueuse/core?module, I encountered an issue where reactivity was not functioning as expected in vueuse. The import process appeared t ...

How can I obtain the index of the selected class name?

Is there a way to retrieve the index of a classname assigned to multiple input fields and then log it using console.log()? I've written this code snippet: document.querySelectorAll('.class-name').forEach(item => { item.addEventListene ...

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

Calculating the number of duplicate lines in a file with node.js

I am currently working on a project where I need to read a large .csv file line by line, extract the first column (which contains country names), and then count the number of duplicates for each country. For example, if the file contains: USA UK USA The ...