正则表达式匹配单个新行。正则表达式匹配双新线 [英] Regex to match single new line. Regex to match double new line
问题描述
我正在尝试构建一个匹配单独换行符( \ n
)的正则表达式。
I am trying to construct a regex that will match a solitary newline character (\n
).
同样,我需要另一个正则表达式来匹配不属于的双重换行符( \ n \ n
)较长的换行符字符,例如 \ n \ n \ n
或 \ n \ nn \ n \ n \\ n \\ n
等。
Similarly, I need another regex to match double newlines (\n\n
) that are not part of a longer run of newline characters like \n\n\n
or \n\n\n\n\n\n
etc.
\ n(?!\ n)
和 \ n \ n(?!\ n)
匹配太多(它们与较长的换行序列中的最后一个换行符匹配)。我该怎么办?
\n(?!\n)
and \n\n(?!\n)
match too much (they match the last newline(s) in a longer sequence of newlines). What can I do instead?
推荐答案
由于JavaScript不支持lookbehind断言,因此您需要匹配一个额外的字符在你的 \
之前,记得稍后处理它(即,如果你使用正则表达式匹配来修改原始字符串,则恢复它)。 / p>
Since JavaScript doesn't support lookbehind assertions, you need to match one additional character before your \
n`s and remember to deal with it later (i.e., restore it if you use the regex match to modify the original string).
(^|[^\n])\n(?!\n)
匹配单个换行符加上前一个字符,
(^|[^\n])\n{2}(?!\n)
匹配双换行加上前一个字符。
matches double newlines plus the preceding character.
所以如果你想要替换一个 \ n
使用< br />
,例如,你必须这样做
So if you want to replace a single \n
with a <br />
, for example, you have to do
result = subject.replace(/(^|[^\n])\n(?!\n)/g, "$1<br />");
对于 \ n \ n
,它是
result = subject.replace(/(^|[^\n])\n{2}(?!\n)/g, "$1<br />");
说明:
( # 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.
这篇关于正则表达式匹配单个新行。正则表达式匹配双新线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!