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

How to Effectively Use Regex in JavaScript for Multiline Matching?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 05:34:02294browse

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
`

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
`

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!

Statement:
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