简体   繁体   English

在python正则表达式中使用OR的最佳方法是什么

[英]What is the best way to use OR in python regex

I'm doing an homework on regex and having some difficulties with OR . 我正在做正则表达式作业,并且在OR上遇到了一些困难。 Given the following strings: 给定以下字符串:

avc7fsrd5vcc12vfscsrwt1qw7eetrs&fsrsy

should return t1 s 应该返回t1 s

fdjhads jhf&5672t3zcxvb,m654godjhfjdyeuyr123jfjjdjfjdfj77djsfhdjhfdsf99 

should return t3 go 123 77 应该返回t3去123 77

The first part is to extract t with some number and then extract s or go depending on what comes first. 第一部分是先提取一定数量的t,然后再提取s或go,具体取决于先到的是什么。 If its go, then we need to extract two numbers afterward, otherwise stop. 如果可行,那么我们需要随后提取两个数字,否则请停止。

This is the regex I'm using 这是我正在使用的正则表达式

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

but it doesn't work when I add an s to the second string and extracts go instead of s. 但是当我在第二个字符串中添加s并提取go而不是s时,它不起作用。

Any help would be appreciated. 任何帮助,将不胜感激。

Its fairly simple. 它相当简单。 The first alternation has priority over the second. 第一个交替优先于第二个。
Just make sure there is no s before go. 只要确保没有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)

Read about regex here: 在这里阅读有关regex信息:

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

Output: 输出:

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

I think this is the regex you need: 我认为这是您需要的正则表达式:

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

It works as per your requirement if i understood you question properly. 如果我理解您提出的问题,它将按您的要求工作。

Demo for 1st match: http://regexr.com/3coi0 第一次比赛的演示: http : //regexr.com/3coi0

Demo for 2nd match : http://regexr.com/3coht 演示第二场比赛: http : //regexr.com/3coht

For more help in understanding advance regex, i'd refer you to read https://www.talentcookie.com/2015/07/lets-practice-regular-expression https://www.talentcookie.com/2016/01/some-useful-regular-expression-terminologies/ 有关了解高级正则表达式的更多帮助,请参考阅读https://www.talentcookie.com/2015/07/lets-practice-regular-expression https://www.talentcookie.com/2016/01/一些无用-正则表达式-术语/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM