Home >Web Front-end >JS Tutorial >How to Match Multiline Content with JavaScript Regular Expressions?

How to Match Multiline Content with JavaScript Regular Expressions?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 20:02:02430browse

How to Match Multiline Content with JavaScript Regular Expressions?

Overcoming JavaScript Regex Boundaries for Multiline Matches

When working with JavaScript regular expressions, it becomes crucial to understand how to match content that spans multiple lines. Consider the following code snippet attempting to extract a PRE block with newlines within it:

<code class="js">var ss = "<pre class="brush:php;toolbar:false">aaaa\nbbb\nccc
ddd"; var arr = ss.match(//gm); alert(arr); // null</code>

The expected outcome is to capture the entire PRE block, but the result is a null alert. To rectify this, we delve into the intricacies of multiline matching.

The '.|[rn]' Gambit

An initial approach involves replacing the . wildcard character with an expression that matches any character or line break: (.|[rn]). However, this proves ineffective.

The Revelation: [sS]

The key to success lies in using [sS] instead of . for multiline matching. This character class encompasses both whitespace and non-whitespace characters, effectively addressing the issue.

<code class="js">var ss = "<pre class="brush:php;toolbar:false">aaaa\nbbb\nccc
ddd"; var arr = ss.match(//gm); alert(arr); // <pre class="brush:php;toolbar:false">...<\/pre></code>

The Subtleties of Greed: '?' vs. ''

Another consideration relates to the quantifier used. While might seem like the obvious choice, it introduces unnecessary greediness. '?' or ' ?' ensures that the match finds the first occurrence instead of the longest possible one.

A Note on [^]

While [^] can also serve as a multiline dot, it is deprecated as per a comment in another post. Therefore, it's better to stick with [sS].

The above is the detailed content of How to Match Multiline Content with JavaScript Regular Expressions?. 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