[英]Javascript regex: only match the end of text
I would like to find out multiline texts ending with "Tr ", "Br " and linebreak ("\\n") without " _" (none-whitespace and underscore) preceded. 我想找出以“Tr”,“Br”和换行符(“\\ n”)结尾的多行文本,前面没有“_”(无空格和下划线)。 Exmples Exmples
Text 1: 文字1:
Command1 Br
Command2 Tr
"Command1 Br \nCommand2 Tr " //match "Tr " at the end
Text 2: 文字2:
Command3 con Tr
Command4 Br
"Command3 con Tr \nCommand4 Br " //match "Br " at the end
Text 3: 文字3:
Command2 Tr
Command3 con Br
Command4 C_
"Command2 Tr \nCommand3 con Br \nCommand4 C_\n" //match "\n" at the end after C_
Text 4: 正文4:
Command1 Tr
Command1 Br
Command2 Tr _
"Command1 Tr \nCommand1 Br \nCommand2 Tr _\n" //no match because of " _" preceded "\n"
Text 5: 文字5:
Command1 Tr
Command1 Br
Command2 mt
"Command1 Tr \nCommand1 Br \nCommand2 mt\n" //match \n at the end after "mt"
Text 6: 正文6:
Command2 ht
"\n\nCommand2 ht\n" //match \n at the end after "ht"
You may use the following regex to extract those matches: 您可以使用以下正则表达式来提取这些匹配项:
/(?:^| [^_]|[^ ]_|[^ ][^_])([BT]r|\n)[\t ]*$/
See the regex demo . 请参阅正则表达式演示 。
Details : 细节 :
(?:^| [^_]|[^ ]_|[^ ][^_])
- a non-capturing group matching one of the three alternatives: (?:^| [^_]|[^ ]_|[^ ][^_])
- 一个非捕获组,匹配三个备选方案之一:
^
- start of a line ^
- 开始一行 |
- or - 要么 [^_]
- space and any char but _
[^_]
- 空格和任何字符但_
|
- or - 要么 [^ ]_
- any char but space and _
[^ ]_
- 任何字符,但空格和_
|
- or - 要么 [^ ][^_]
- any char but space and then any char but _
(thus, no space
+ _
) [^ ][^_]
- 任何char但空格然后是任何char但是_
(因此,没有space
+ _
) ([BT]r|\\n)
- Capturing group 1: either Br
, Tr
or a newline symbol ([BT]r|\\n)
- 捕获组1: Br
, Tr
或换行符号 [\\t ]*
- 0+ horizontal whitespaces (may be replaced with [^\\S\\r\\n]
for better hor. whitespace coverage) [\\t ]*
- 0+水平空格(可以替换为[^\\S\\r\\n]
以获得更好的空白空间覆盖率) $
- the very end of the string. $
- 字符串的结尾。 var ss = ["Command1 Br \\nCommand2 Tr ", "Command3 con Tr \\nCommand4 Br ", "Command2 Tr \\nCommand3 con Br \\nCommand4 C_\\n", "Command1 Tr \\nCommand1 Br \\nCommand2 Tr _\\n", "Command1 Tr \\nCommand1 Br \\nCommand2 mt\\n", "\\n\\nCommand2 ht\\n"]; var rx = /(?:^| [^_]|[^ ]_|[^ ][^_])([BT]r|\\n)[\\t ]*$/; for (var s of ss) { console.log("Looking for a match in: " + s); m = rx.exec(s); if (m) { console.log("Found: " + JSON.stringify(m[1], 0, 4)); } else { console.log("No Match Found."); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.