Home > Web Front-end > JS Tutorial > How to Effectively Use Regex in JavaScript for Multiline Matching?

How to Effectively Use Regex in JavaScript for Multiline Matching?

Mary-Kate Olsen
Release: 2024-11-03 05:34:02
Original
330 people have browsed it

How to Effectively Use Regex in JavaScript for Multiline Matching?

Utilizing Regex in JavaScript Across Multiple Lines

In JavaScript, the 'm' flag, supposedly designed for multiline matching, fails to capture content spanning across newlines. To resolve this, a more robust solution is required.

The key is to employ either '[sS]' or '[^]' as the multiline dot. These patterns match any character, including newlines. This approach effectively captures content regardless of its distribution over multiple lines.

Example:

var ss = "<pre class="brush:php;toolbar:false">aaaa\nbbb\nccc
ddd"; var arr = ss.match( /
[\s\S]*?<\/pre>/gm );
console.log(arr); // Outputs: `<pre class="brush:php;toolbar:false">aaaa\nbbb\nccc
`
Copy after login

Less Cryptic Alternative:

While the provided solution is effective, a less intricate approach can be achieved by replacing '[sS]' with '.*?'. This quantifier matches any number of characters (including newlines) non-greedily, resulting in more efficient and targeted matching.

var arr = ss.match( /<pre class="brush:php;toolbar:false">.*?<\/pre>/gm );
console.log(arr); // Outputs: `<pre class="brush:php;toolbar:false">aaaa\nbbb\nccc
`
Copy after login

Tips:

  • Avoid excessive greediness by using non-greedy quantifiers like '*?' or ' ?' whenever possible.
  • Benchmarks indicate that '[^]' offers superior performance compared to other methods.
  • Although '[^]' is deprecated, it remains an effective solution in older environments.

The above is the detailed content of How to Effectively Use Regex in JavaScript for Multiline Matching?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template