What is the best way to use OR in python regex

↘锁芯ラ 提交于 2019-12-23 23:13:27

问题


I'm doing an homework on regex and having some difficulties with OR. Given the following strings:

avc7fsrd5vcc12vfscsrwt1qw7eetrs&fsrsy

should return t1 s

fdjhads jhf&5672t3zcxvb,m654godjhfjdyeuyr123jfjjdjfjdfj77djsfhdjhfdsf99 

should return t3 go 123 77

The first part is to extract t with some number and then extract s or go depending on what comes first. 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.

Any help would be appreciated.


回答1:


Read about regex here:

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

Output:

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



回答2:


Its fairly simple. The first alternation has priority over the second.
Just make sure there is no s before go.

(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:


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

Demo for 2nd match : 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://stackoverflow.com/questions/35282775/what-is-the-best-way-to-use-or-in-python-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!