haiyang416

请教一个正则表达式分组捕获的问题

  •  
  •   haiyang416 · Dec 9, 2015 · 2279 views
    This topic created in 3845 days ago, the information mentioned may be changed or developed.
    示例文本 1 : all directions are: n, w, s and e.
    目标结果 1 :{n, w, s, e}

    示例文本 2 : all directions are: nw, sw, se, w, s and e.
    目标结果 2 :{nw, sw, se, w, s, e}

    只用一条正则表达式,是否可以捕获目标结果中的所有分组?
    2 replies    2015-12-09 16:07:33 +08:00
    haiyang416
        1
    haiyang416  
    OP
       Dec 9, 2015
    人工顶置一次。
    SpicyCat
        2
    SpicyCat  
       Dec 9, 2015
    你没有说你用的什么语言。

    假设你用 Python
    (?:\s*(?::|,|and)\s*(?P<target>\w+))
    这条正则产生了名为 target 的 named group

    如果你用 Ruby
    (?:\s*(?::|,|and)\s*(?<target>\w+))

    如果你用 php ,那么上面两条都能用

    如果你用 javascript ,因为 js 不支持 named capturing group ,所以只能用 numbered capturing group
    (?:\s*(?::|,|and)\s*(\w+))

    原理:每组以 : 或者 , 或者 and 开头,前后可能有空格(\s*),然后接一个或者多个英文字符(\w+), 这里的\w+就是我们要找的内容。
    如果你的需求确定只会出现 nw, sw, se, w, s, e 这几种组合,那么也可以缩小匹配范围。

    正则测试网站: https://regex101.com/#pcre
    这是 Python, Javascript 和 php 的

    http://rubular.com/
    这是 Ruby 的

    你可以自己测试修改正则。
    其他语言可以自己修改,大同小异。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2713 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 14:08 · PVG 22:08 · LAX 07:08 · JFK 10:08
    ♥ Do have faith in what you're doing.