我有以下字符串:
一个。 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}=if
和{2}=specific_condition
{1}=if
,{2}=specific_condition
和{3}=then
{1}=if
,{2}=specific_condition
,{3}=then
和{4}=specific_function
答案 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) *(.*))?/)
答案 1 :(得分:0)
试试这个:
/(if) *(.*?) (then)? *(.*)/
我通过在线正则表达式测试人员进行了测试,并且所有3个表达式都匹配了。