Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx, matching a whole word that has an optional ending

Tags:

regex

With the following guide in mind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Why does this not match words that end with foo or foobar?

/[0-9a-zA-Z]+foo(?:bar)*\b/i

It's supposed to be part of a wordfilter for 4chan.orgs technology board, applied by an addon called 4chanX. I pretty much pasted the code verbatim to filter comments containing the words.

like image 918
Erius Avatar asked Sep 02 '25 10:09

Erius


1 Answers

There is no need of *, a ? will do it for you.

/[0-9a-zA-Z]+foo(?:bar)?\b/i

also if you're trying to find all words of that pattern in your string, you should add g modifier if it's available for your regex engine:

/[0-9a-zA-Z]+foo(?:bar)?\b/ig
like image 186
revo Avatar answered Sep 05 '25 02:09

revo