Search code examples
regexregexp-replace

Insert characters (hyphens) between matches in RegEx


I am using Regular Expressions to find very simple patterns.

However, I want to insert a hyphen character between the matches.

I'm very familiar with writing RegEx Match patterns, but struggling with how to use RegEx replace to insert characters.

My RegEx is:
(\d{1,2})([A-Z]{1,3})(_)?(\d{3,4})
which matches:

  • 03EM0109
  • 03EM0112
  • 03EM0151
  • 3V204
  • 02SDV_0900

I would like the output, using RegEx Replace, to input hyphens between the matches to give me:

  • 03-EM-0109
  • 03-EM-0112
  • 03-EM-0151
  • 3-V-204
  • 02-SDV-0900

I tried changing the RegEx and entering numbered capture groups for null patterns between, but when using a replace function this returns only hyphens. Presumably because the null capture group is not actually capturing anything?

Using:
(\d{1,2})()([A-Z]{1,3})()(_)?()(\d{3,4})

And replacing with $2-$4-$5-
Returns 3 hyphens - - -

Could someone please help....


Solution

  • If you use the RegExp (\d{1,2})([A-Z]{1,3})_?(\d{3,4}), and replace with $1-$2-$3 then it seems to produce the desired results. I removed the capture group around the underscore