Regex for $gme or gme with space or no space after or before it in python

Viewed 56

I want a regex that can find all $gme or gme. It should not find $gme or gme in a string like

hello $gmee

or

hello g$gme

So for example in a string such as

Hello gme. Hey $gme. Hey $gmee. Hey gmee.

It should find only gme or $gme from the above string.

It must also find gme or $gme when there is no space before or after a string For example

$gme

or

gme

I am writing a script that can count the number of times $gme or gme is mentioned in a string

So in a string like

Hello gme. Hey $gme. Hey $gmee. Hey gmee.

Its mentioned only two times.

I hope its clear now.

Regex I have tried

\$gme$|\sgme\s|\sgme|^gme\S

See the demo screenshot.

The above one fails when there is no space before and after $gme or gme. And also it includes gmee and $gmee which I don't want to include.

1 Answers

You can use use a mix of whitespace and word boundaries:

(?<!\S)\$?gme\b

See the regex demo

Details:

  • (?<!\S) - a negative lookbehind that fails the match if there is no non-whitespace char immediately to the left of the current position (so, start of string or a whitespace must occur immediately on the left)
  • \$? - an optional $ char
  • gme - a word
  • \b - a word bounary.
Related