Home > Software engineering >  Regular expression ignoring dash or hyphen at the middle of text
Regular expression ignoring dash or hyphen at the middle of text

Time:09-23

I am trying to figure out how I can ignore the hyphen or dash as seen below

chug-jug

/chugjug/i should match with chug-jug. Thank you!

Some other examples include:

I-no match with /ino/i

Jack-O match with /jacko/i

CodePudding user response:

Since you tagged the question with ignoring hyphens can be easily achieved by removing them before matching the string against your current regex.

"chug-jug"
  .replace(/-/g, "") // remove all hyphens from the string
  .match(/chugjug/i) // match the string against your regex

CodePudding user response:

Here is a solution for the i-no case:

/i-?n-?o-?/i

Explanation:

  • -? means zero or one dash
  • we have to add it after each letter. Without this the pattern would be /ino/i
  • The trailing /i means case insensitive

Demo here.

Alternative solution: remove the dashes with replace.

CodePudding user response:

Seems like you want something like this :

/c[^chugjug]*?h[^chugjug]*?u[^chugjug]*?g[^chugjug]*?j[^chugjug]*?u[^chugjug]*?g[^chugjug]*?/g

demo here : https://regex101.com/r/wU6izW/1

  • Related