2

Using regular expressions, how do I find a particular word followed by a space followed by a number?

Example:

Bug 125

Where "Bug" is should always be the first word found in a line of text followed by a space and then a number and nothing else.

In other words, I don't want to find "Bug 125" as written within some paragraph in the same text file I am parsing.

I haven't tried much because I am terrible at regular expressions. Any help is appreciated.

everton
  • 6,827
  • 2
  • 24
  • 41
Matt Cashatt
  • 20,878
  • 24
  • 73
  • 105

2 Answers2

6

Sounds like you want this:

^Bug [0-9]+$

Where:

  • ^ = Starts with
  • [0-9]+ = One ore more digits
  • $ = Ends with this
Sebastian Zartner
  • 16,477
  • 8
  • 74
  • 116
Timeout
  • 7,191
  • 23
  • 35
  • +1 Setting "multiline mode" on the regex engine options probably would be a good idea. – everton Feb 27 '14 at 02:42
  • 1
    I hate using `\d` as it kinda obfuscates things. I prefer `[0-9]` as it is clear that we are using the numbers 0 to 9. But that's just my personal preference. – Shadow Man Feb 27 '14 at 02:43
  • @ShadowCreeper: Someone mentioned on another SO question recently that `[0-9]` is indeed preferable - for a small performance gain but, more importantly, also because `\d` will technically match Unicode characters other than the digits 0-9. This is something to watch for. – J0e3gan Feb 27 '14 at 03:01
  • 1
    @ShadowCreeper: Aforementioned mention of `\d`'s looseness - [http://stackoverflow.com/a/21950819/1810429](http://stackoverflow.com/a/21950819/1810429). – J0e3gan Feb 27 '14 at 03:24
  • 1
    @J0e3gan Thanks for the link. This is good to know. And that comment points to a more exhaustive list of unicode digits here: http://stackoverflow.com/questions/16621738/d-is-less-efficient-than-0-9/16621778#16621778 – Shadow Man Feb 27 '14 at 19:09
0

This should do it:

^Bug [0-9]+$
  • "^" - begining of the line
  • "Bug " - the word and follow-on space you want to match
  • "[0-9]" - a digit 0-9
  • "+" - one or more (digits)
  • "$" - end of the line
J0e3gan
  • 8,287
  • 9
  • 48
  • 76