我有以下字符串:
A. 如果特定条件则特定函数
这是字符串的最长变体,也可能通过以下方式发生:
B. 如果特定功能则
C. 如果特定功能
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
我想要做的是提出一个正则表达式来匹配所有字符串变体并捕获相关组:
- 如果我有字符串 C.,它会匹配并捕获
{1}=if
和{2}=specific_condition
- 如果我有字符串 B.,它会匹配并捕获
{1}=if
、{2}=specific_condition
和{3}=然后
- 如果我有字符串 A.,它会匹配并捕获
{1}=if
、{2}=specific_condition
、{3}=then
和{4}=special_function
最佳答案
试试这个:
“如果特定函数则特定函数”.match(/(if) *(.*?)(?=then|$)(?:(then) *(.*))?/)
“如果特定函数则”.match(/(if) *(.*?)(?=then|$)(?:(then) *(.*))?/)
"if Specific_function".match(/(if) *(.*?)(?=then|$)(?:(then) *(.*))?/)
关于javascript - 正则表达式捕获特定字符串之前的所有内容,然后逐步捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27972595/