正则表达式捕获特定字符串之前的所有内容,然后逐步捕获

Regex to capture everything before specific string and then progressively

我有以下字符串:

一个。 if specific_condition then specific_function

这是字符串的最长变体,它也可能以下列方式出现:

乙。 if specific_function then

C。 if specific_function

specific_condition 类似于多字串,例如我的名字是欧比。所以一个完全定义的字符串可以是 if my name is obi then doFunction();

我有以下正则表达式:

/(if) *(.*?)(?=then|$)(then) *(.*)/

哪个会匹配:

if specific_condition then specific_function
if specific_condition then

但它不匹配:

if specific_condition

我想做的是想出一个正则表达式来匹配所有字符串变体并捕获相关组:

  1. 如果我有字符串 C.,它会匹配并捕获 {1}=if{2}=specific_condition
  2. 如果我有字符串 B.,它会匹配并捕获 {1}=if{2}=specific_condition{3}=then
  3. 如果我有字符串 A.,它会匹配并捕获 {1}=if{2}=specific_condition{3}=then{4}=specific_function

试试这个:

"if specific_function then specific_function".match(/(if) *(.*?)(?=then|$)(?:(then) *(.*))?/)

"if specific_function then".match(/(if) *(.*?)(?=then|$)(?:(then) *(.*))?/)

"if specific_function".match(/(if) *(.*?)(?=then|$)(?:(then) *(.*))?/)

http://jsfiddle.net/cqebLv4h/

试试这个:

/(if) *(.*?) (then)? *(.*)/

我通过在线正则表达式测试人员进行了测试,您的所有 3 个表达式都匹配。