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

时间:2015-01-15 20:41:32

标签: javascript regex

我有以下字符串:

一个。 if specific_condition then specific_function

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

B中。 if specific_function then

℃。 if specific_function

specific_condition类似于多字符串,例如我的名字是obi。所以完全定义的字符串可以是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

2 个答案:

答案 0 :(得分:1)

试试这个:

"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/

答案 1 :(得分:0)

试试这个:

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

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