Javascript正则表达式:只匹配文本的结尾

时间:2017-04-24 04:36:03

标签: javascript regex

我想找出以" Tr"," Br"结尾的多行文字。并且换行(" \ n")没有" _" (无空格和下划线)之前。 Exmples

文字1:

Command1 Br 
Command2 Tr 

"Command1 Br \nCommand2 Tr " //match "Tr " at the end

文字2:

Command3 con Tr 
Command4 Br 

"Command3 con Tr \nCommand4 Br " //match "Br " at the end

文字3:

Command2 Tr 
Command3 con Br 
Command4 C_

"Command2 Tr \nCommand3 con Br \nCommand4 C_\n" //match "\n" at the end after C_

文字4:

Command1 Tr 
Command1 Br 
Command2 Tr _

"Command1 Tr \nCommand1 Br \nCommand2 Tr _\n" //no match because of " _" preceded "\n"

文字5:

Command1 Tr 
Command1 Br 
Command2 mt

"Command1 Tr \nCommand1 Br \nCommand2 mt\n" //match \n at the end after "mt"

文字6:

Command2 ht

"\n\nCommand2 ht\n" //match \n at the end after "ht"

1 个答案:

答案 0 :(得分:1)

您可以使用以下正则表达式来提取这些匹配项:

/(?:^| [^_]|[^ ]_|[^ ][^_])([BT]r|\n)[\t ]*$/

请参阅regex demo

<强>详情:

  • (?:^| [^_]|[^ ]_|[^ ][^_]) - 与三种选择之一匹配的非捕获组:
    • ^ - 开始行
    • | - 或
    • [^_] - 空格和任何字符_
    • | - 或
    • [^ ]_ - 任何字符空格和_
    • | - 或
    • [^ ][^_] - 任何字符空格,然后是_的所有字符(因此,没有space + _
  • ([BT]r|\n) - 捕获第1组:BrTr或换行符号
  • [\t ]* - 0+个水平空格(可以替换为[^\S\r\n]以获得更好的空白空间覆盖率)
  • $ - 字符串的最后一部分。

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.");
  }
}