【问题标题】:Complicated Regex Capturing - Javascript复杂的正则表达式捕获 - Javascript
【发布时间】:2015-07-04 17:04:17
【问题描述】:

我一直在尝试捕捉下面的部分

a1A ^(?\..*+) and a1A ^(?\..*+) g:a1A ^(?\..*+)

但是,我无法为我想要实现的目标创建 100% 有效的正则表达式。

正则表达式必须捕获字母后跟冒号开头的任何内容以及冒号之前的字母,然后它必须捕获第一次匹配后跟冒号的字母以及冒号之前的字母直到空格。例如对于下面的这一行:

x:a1A ^(?\..*+) z:a1A ^(?\..*+) g:a1A ^(?\..*+)

--> captured value must be 'x', 'a1A ^(?\..*+)', 'z', and 'a1A ^(?\..*+) g:a1A ^(?\..*+)'

另一个例子

x23:a1A ^(?\..*+) z:a1A ^(?\..*+) g:a1A ^(?\..*+)

--> captured value must be 'x23', 'a1A ^(?\..*+)', 'z' and 'a1A ^(?\..*+) g:a1A ^(?\..*+)'

然后如果没有以任何字母开头并后跟冒号的字符串,那么它必须捕获任何内容,直到空格后跟一个字母或多个字母和一个冒号。例如

a1A ^(?\..*+) s:a1A ^(?\..*+)

--> captured value must be 'a1A ^(?\..*+)', 's' and 'a1A ^(?\..*+)

【问题讨论】:

  • 您是不是故意不拆分前两个示例中的g:a1A 部分?它也部分出现在第三个示例中,这就是为什么它看起来可能是一个错字。假设您的意思是前两个示例的最后捕获的组是'a1A ^(?\..*+)' 'g' and 'a1A ^(?\..*+)',我将发布一个答案。
  • @machee 是的,抱歉,我编辑了我的问题并修复了最后一个示例,它必须在前 2 个示例中捕获第三个字母:anychar 模式,只有前 2 个字母:anychar 模式是分隔符。

标签: javascript regex


【解决方案1】:

我想出的正则表达式是?:([^: ]+):)?([^ ]+ [^ ]+)(?: |$)

(?:([^: ]+):)?  // don't capture the colon, capture the part before the colon
([^ ]+ [^ ]+)   // capture the two groups that may or may not be preceded by the colon
(?: |$)         // end at either a space or the end of the line/string

这是我测试过的小提琴:http://jsfiddle.net/9nbsu84v/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2016-02-10
    • 2013-10-31
    • 1970-01-01
    相关资源
    最近更新 更多