【问题标题】:Regex to capture everything before specific string and then progressively正则表达式捕获特定字符串之前的所有内容,然后逐步
【发布时间】:2015-01-16 05:09:15
【问题描述】:

我有以下字符串:

A. if specific_condition then specific_function

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

B. 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

【问题讨论】:

    标签: javascript regex


    【解决方案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/

    【讨论】:

    • 它只匹配两个字符串变体?!
    • 谢谢。为了更清楚,我编辑了这个问题。我之前使用的是 RegexBuddy,但我没有启用选项^$ match at linebreaks。当我做一切工作。干杯。
    【解决方案2】:

    试试这个:

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

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

    【讨论】:

    • 它也匹配 "if specific_function specific_function".match(/(if) *(.*?)(?=then|$)(?:(then) *(.*))?/) 第四个参数...我认为不应该匹配...但我不确定
    • 为了更清楚,我编辑了这个问题。这不能正确捕获组。例如,当使用“if my name is obi then doSomething()”时,我得到{1}=if{2}=my{4}=name is obi then doSomething()
    猜你喜欢
    • 2018-12-11
    • 2011-08-24
    • 1970-01-01
    • 2023-01-10
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    相关资源
    最近更新 更多