正则表达式匹配单个新行。正则表达式匹配双新行

2023-11-25

我正在尝试构建一个正则表达式来匹配一个单独的换行符(\n).

同样,我需要另一个正则表达式来匹配双换行符(\n\n)不属于较长的换行符,例如\n\n\n or \n\n\n\n\n\n etc.

\n(?!\n) and \n\n(?!\n)匹配太多(它们匹配较长换行符序列中的最后一个换行符)。我能做什么呢?


由于 JavaScript 不支持后向断言,因此您需要匹配一个附加字符before your \n`s,并记住稍后处理它(即,如果使用正则表达式匹配修改原始字符串,则恢复它)。

(^|[^\n])\n(?!\n)

匹配单个换行符加上前面的字符, and

(^|[^\n])\n{2}(?!\n)

匹配双换行符加上前面的字符。

所以如果你想更换一个\n with a <br />,例如,你必须做

result = subject.replace(/(^|[^\n])\n(?!\n)/g, "$1<br />");

For \n\n, it's

result = subject.replace(/(^|[^\n])\n{2}(?!\n)/g, "$1<br />");

看到它regex101

解释:

(       # Match and capture in group number 1:
 ^      # Either the start of the string
|       # or
 [^\n]  # any character except newline.
)       # End of group 1. This submatch will be saved in $1.
\n{2}   # Now match two newlines.
(?!\n)  # Assert that the next character is not a newline.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正则表达式匹配单个新行。正则表达式匹配双新行 的相关文章

随机推荐