Merge several regular expressions into one RE

前端 未结 5 2385
暖寄归人
暖寄归人 2021-02-13 02:04

I have written 2 REs to match several string sequences in a String. for e.g. lets assume the two regular expressions are RE1, RE2. The strings can be i

5条回答
  •  -上瘾入骨i
    2021-02-13 02:28

    I thought of using 'or' | but the problem with that is regex will stop matching once it finds the first matching sequence and not continue to find others.

    That's what re.findall is for.

    >>> import re
    >>> RE = r'(?:\d{1,3}[a-zA-Z]?/\d{1,3}[a-zA-Z]?)|(?:\babc\b)'
    >>> string = '*some string* 100/64h *some string* 120h/90 *some string* abc 200/100 abc *some string* 100h/100f'
    >>> re.findall(RE, string)
    ['100/64h', '120h/90', 'abc', '200/100', 'abc', '100h/100f']
    

    Note the usage of non-capturing parentheses (the (?:...) stuff). If the regex used capture-grouping parentheses as normal, re.findall would return [('100/64h', ''), ('120h/90', ''), ('', 'abc'), ('200/100', ''), ('', 'abc'), ('100h/100f', '')].

提交回复
热议问题