Home > Enterprise >  Regex to match everything right of a "-" but whole string if no "-" exists
Regex to match everything right of a "-" but whole string if no "-" exists

Time:11-15

I am trying to figure out a way to have a regex that returns the whole string, if no "-" is found in the string. But if there is a "-", it should only return everything to the right of that "-".

For example:

  • "Text" should return "Text"
  • "Sample-Text" should return "Text"

So far, i figured out how to solve the second part: (?<=-).* returns everything after a "-". However, i am completely stuck figuring out how to combine that and return everything if there is no "-".

Any help would be greatly appreciated!

CodePudding user response:

You can use a character set that excludes "-":

[^-]*$

Demo: https://regex101.com/r/yRm59e/1

  • Related