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

后端 未结 3 1882
栀梦
栀梦 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条回答
  • 2021-02-02 10:13

    You can try

    ^\s*-
    
    • ^: start of string
    • \s*: zero or more whitespace characters
    • -: a literal - (you don't need to escape this outside a character class)
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-02 10:18

    You can use this regex by making 0 or more spaces optional match at beginning:

    ^\s*-
    
    0 讨论(0)
提交回复
热议问题