Home > Mobile >  Regular Expression - Get Strings Before and After First Spaced Hyphen
Regular Expression - Get Strings Before and After First Spaced Hyphen

Time:08-04

I know this can be done via string splitting but I'm actually interested in the regex solution for this. Basically, I would like to retrieve the entire string before and after a spaced hyphen (" - "). I've tried:

^[^-]*

And this works for strings like

EK725 - London to Paris

But once there is a non-spaced hyphen like

EK-725 - London to Paris

It breaks down. Using ^[^ - ]* also does not seem to work. Also, I am not sure what the syntax would be to retrieve the text after the spaced hyphen. What would be the solution?

CodePudding user response:

Does this work for you?

(^. (?= - ))|((?<= - ). $)

Check a demo

CodePudding user response:

This should work

[a-zA-Z] ([ -]?(?=\.\d|\d)(?:\d )?(?:\.?\d*))(?:[eE]([ -]?\d ))? - ([a-zA-Z] ( [a-zA-Z] ) )

Really neat tool with a GUI if you want to try it yourself. https://regex-generator.olafneumann.org/

  • Related