简体   繁体   English

Javascript正则表达式匹配跳回新行

[英]Javascript regex match skipping back to back new line

So I have this string:所以我有这个字符串:

function abc() {\n\n    return def;\n}

And I use this:我用这个:

string.match(/[^\r\n]+/g)

And it matches into 3 lines:它匹配成 3 行:

Match 1: function abc() {匹配 1:函数 abc() {

Match 2: return def;第 2 场:返回 def;

Match 3: }第 3 场比赛:}

But it is missing a fourth match which should be the new line with no characters after the '{'.但是它缺少第四个匹配项,该匹配项应该是“{”后没有字符的新行。

I am using the website https://regex101.com/r/ALvFIN/1/ to test.我正在使用网站https://regex101.com/r/ALvFIN/1/进行测试。

Set to flavor: ECMAScript设置为风味:ECMAScript

Regex: /[^\\r\\n]+/g正则表达式:/[^\\r\\n]+/g

Test String:测试字符串:

function abc() {

    return def;
}

Any idea how to correctly match the double \\n\\n with no characters on line 2?知道如何正确匹配第 2 行没有字符的双 \\n\\n 吗? I have tried the whitespace \\s and \\S but not right.我试过空格 \\s 和 \\S 但不对。 Starting to think I need to look at an alternative solution.开始认为我需要寻找替代解决方案。

You seem to want to match a string of one or more non-linebreak chars or an empty line.您似乎想要匹配由一个或多个非换行符或空行组成的字符串。

This logic means you simply want to split a string with a single line break sequence .这种逻辑意味着您只想用单个换行符序列拆分字符串

To match ASCII line breaks, CRLF, LF or CR, you can use /\\r\\n?|\\n/ .要匹配 ASCII 换行符、CRLF、LF 或 CR,您可以使用/\\r\\n?|\\n/

To match any Unicode line break sequence, you can use /\\r\\n|[\\r\\n\\f\ \…\
\
]/ .要匹配任何 Unicode 换行符序列,您可以使用/\\r\\n|[\\r\\n\\f\ \…\
\
]/

 console.log("function abc() {\\n\\n return def;\\n}".split(/\\r\\n?|\\n/)) // Any Unicode line break sequence: var rx = /\\r\\n|[\\r\\n\\f\\…\
\
]/; console.log("function abc() {\\n\\n return def;\\n}".split(rx))

And if you still want to use .match() simply add a ^$ alternative to your regex with /m flag to make ^ and $ match start/end of a line:如果你仍然想使用.match()只需添加一个^$替代你的正则表达式/m标志使^$匹配行的开始/结束:

 console.log("function abc() {\\n\\n return def;\\n}".match(/[^\\r\\n]+|^$/gm))

If you want to split the string into its constituent lines, you can use this: /^.*$/gm .如果要将字符串拆分为其组成行,可以使用以下命令: /^.*$/gm Note the m option to enable multiline matching.请注意启用多行匹配的m选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM