Ghoul Fool
Ghoul Fool

Reputation: 6967

Substring word boundaries with regex

I'm 99% of there with a regex to find words, but not any iterations of where that occurs as a substring.

ie Looking for jam or JAM but not Pajama or florojam

This is what I have so far:

\bjam\s?\d?\b

It works with all the combinations I'm likely to encounter except that I would like it to also pick up on multiple iterations of the same string with no spaces

jamjamjamjam

Is there away I can add that to the regex?

Upvotes: 1

Views: 421

Answers (2)

anubhava
anubhava

Reputation: 785846

You may use this regex with alternation:

~\b(?:(?:jam)+|jam\h*\d*)\b~i

RegEx Demo

RegEx Details:

  • \b: Word boundary
  • (?:(?:jam)+|jam\h*\d*): Match 1+ adjacent jam strings or jam followed by 0+ whitespaces and 0+ digits
  • \b: Word boundary
  • i: mode for ignore case

Upvotes: 5

Alexandre Elshobokshy
Alexandre Elshobokshy

Reputation: 10922

You could try something like this :

\b(?:jam|JAM)+\b

https://regex101.com/r/C05fsI/4

Upvotes: 1

Related Questions