Search code examples
pythonregexregressionqregularexpression

RegEx to accept String, # and a number


I am trying to add the commit message hook to accept the following inputs in Gitlab:

bug 12345
bug #12345
BUG # 12345
Bug#12345
bug12345

The number 12345 should be changed to anything which is either a 5 digit or 6 digit number (not less than that, not greater than that)

It should get started from Bug, BUG or bug.

It should not have any other character than # or space or blank that too just between the numbers and string "Bug/bug/BUG"

I need help with this ASAP.

I have tried to achieve this by :

^(BUG|bug|Bug)\ |#\d+

but this is not giving the desired output. I am taking reference from :

  1. https://regex101.com/
  2. https://github.com/google/re2/wiki/Syntax

Thanks a lot in advance.


Solution

  • You can use

    ^(BUG|bug|Bug) *(?:# *)?\d{5,6}$
    

    See the regex demo

    If you just want to match bug in a case insensitive way, you can write it as (?i)^Bug *(?:# *)?\d{5,6}$.

    To match any whitespace, replace the literal spaces in the pattern with a \s construct.

    More details:

    • ^ - start of string
    • (BUG|bug|Bug) - BUG, bug, or Bug
    • *(?:# *)? - zero or more spaces followed with an optional sequence of a # followed with zero or more spaces
    • \d{5,6} - five or six digits
    • $ - end of string.