Home > Mobile >  Use Regex to get last substring, separated by hyphens
Use Regex to get last substring, separated by hyphens

Time:11-22

I need to parse out the "permission" substring from group names, however I have two patterns this group names follow:

gcp-edp-platform-dgov-nonprod-oneil-(permission)
gcp-edp-platform-dgov-prod-atp-(permission).groups

Either the group name ends with the permission substring, or it ends with the permission substring.groups.

I need to be able to extract just the permission substring without grabbing the .groups.

I know just .*-(.*) get me everything after the last hyphen but it still grabs the .groups for the names that do have it. Can someone help me create a regex for this instance?

CodePudding user response:

Use look arounds:

(?<=-)[^-.] (?!.*-)

See live demo.

This works with the examples given (ie assumes permissions does not contain dashes or dots).

CodePudding user response:

You can use

.*-(.*?)(?:[.]groups)?$

See the regex demo. Details:

  • .* - any zero or more chars other than line break chars as many as possible
  • (.*?) - Group 1: any zero or more chars other than line break chars as few as possible
  • (?:[.]groups)? - an optional sequence of .groups
  • $ - end of string.
  • Related