Regular Expression match lines starting with a certain character OR whitespace and then that character

后端 未结 3 1881
栀梦
栀梦 2021-02-02 10:03

I am trying to write a regular expression that matches lines beginning with a hyphen (-) OR that begins with spaces or tabs and then has a hyphen. So it should match the followi

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 10:13

    the above (using \s*) is the easiest one for this case, but in general, you can always use the | syntax:

    re.match('^-|^\s+-', '- hello')
    <_sre.SRE_Match object at 0x0000000054E72030>
    
    re.match('^-|^\s+-', '     - hello')
    <_sre.SRE_Match object at 0x0000000054E72030>
    
    re.match('^-|^\s+-', '     + hello')
    None
    

    ^- is the case for - at beginning, `^\s+-' is with one or more spaces, and | chooses either one.

提交回复
热议问题