简体   繁体   中英

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 Pa jam a or floro jam

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?

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

You could try something like this :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM