Home > OS >  Regex for finding string after nth occurrence of hyphen
Regex for finding string after nth occurrence of hyphen

Time:11-04

I have the multiple rows of strings that look like the following:

irm-eap-edp-refined-nonprod
irm-eap-edp-reporting-prod
irm-eap-edp-development-nonprod

I need to extract the nonprod or prod string from each, it will always be after the 4th hyphen and the last substring of the entire string.

What's a simple regex for this situation?

CodePudding user response:

If you want the last substring after - you can do:

.*-(.*)

Regex demo.

CodePudding user response:

You could substitute everything starting with 4 [^-] - chunks with nothing:

/^(?:[^-] -){4}//gm
  • ^ start of line anchor
  • [^-] - match on anything but - 1 or more times followed by a -
  • (?: ... ) - non capturing group
  • {4} - four times

Demo

  • Related