Search code examples
regexstringlookbehindnegative-lookbehind

How can I use regex to match both single word strings and hyphenated strings?


I am trying to match the first word after a specific string using regex and have been struggling to make all instances work properly. Let's say I have 2 strings:

Site Code: foobar

Site Code: hello-world

Now, using (?<=\bSite Code:\s)(\w+) returns foobar which is correct, but only returns hello when I need hello-world instead.

So, I changed my expression to (?<=\bSite Code:\s)(\w+)(-\w+) in order to pickup the hyphenated words, but now it is ignoring the non-hyphenated words.

Is there a way to get both foobar and hello-world from the same expression?


Solution

  • Try this regex:

    (?<=\bSite Code:\s)([-\w]+)
    
    #\w only include the range [A-Za-z0-9_] in ascii mode.