【问题标题】:What is the best way to use OR in python regex在 python 正则表达式中使用 OR 的最佳方法是什么
【发布时间】:2016-05-18 21:22:40
【问题描述】:

我正在做一个关于正则表达式的作业,并且在使用 OR 时遇到了一些困难。 给定以下字符串:

avc7fsrd5vcc12vfscsrwt1qw7eetrs&fsrsy

应该返回 t1 s

fdjhads jhf&5672t3zcxvb,m654godjhfjdyeuyr123jfjjdjfjdfj77djsfhdjhfdsf99 

应该返回 t3 go 123 77

第一部分是用某个数字提取 t 然后提取 s 或 go 取决于先出现的内容。如果成功,那么我们需要在之后提取两个数字,否则停止。

这是我正在使用的正则表达式

 '(t[0-9]).*?(go).*?([0-9]+).*?([0-9]+)|(t[0-9]).*?(s)'

但是当我将 s 添加到第二个字符串并提取 go 而不是 s 时,它不起作用。

任何帮助将不胜感激。

【问题讨论】:

  • then we need to extract two numbers afterward什么之后?
  • 第二个样本 t3...go...123...77 因为 654 在 go 之前

标签: python regex python-2.7 python-2.x


【解决方案1】:

在此处了解regex

print re.findall(r'(t\d+).*?(s|go)\D*(\d*)\D*(\d*)', s)

输出:

[('t3', 'go', '123', '77')]

【讨论】:

    【解决方案2】:

    它相当简单。第一个交替优先于第二个。
    去之前确保没有s

    (t[0-9])[^s]*?(go).*?([0-9]+).*?([0-9]+)|(t[0-9]).*?(s)

    Formatted and tested:

        ( t [0-9] )                   # (1)
        [^s]*? 
        ( go )                        # (2)
        .*? 
        ( [0-9]+ )                    # (3)
        .*? 
        ( [0-9]+ )                    # (4)
     |  
        ( t [0-9] )                   # (5)
        .*? 
        ( s )                         # (6)
    

    【讨论】:

    • 感谢您的帮助。我对正则表达式相当陌生。真的很感激。
    【解决方案3】:

    我认为这是您需要的正则表达式:

                          (t\d+).*?(go|s)\D*?(\d*)\D*?(\d*)
    

    如果我正确理解您的问题,它会按照您的要求工作。

    第一场比赛演示: http://regexr.com/3coi0

    第二场比赛演示 : http://regexr.com/3coht

    有关了解高级正则表达式的更多帮助,我建议您阅读 https://www.talentcookie.com/2015/07/lets-practice-regular-expression https://www.talentcookie.com/2016/01/some-useful-regular-expression-terminologies/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 2011-04-16
      • 1970-01-01
      相关资源
      最近更新 更多