Reputation: 6892
I want to match two groups of strings that comes before and after the hyphen. However, in some cases the hyphen can also be missing. So what I want is:
"Hello World - This is a test": group(1) = Hello World, group(2) = This is a test
"Hello World": group(1) = Hello World, group(2) missing
I've tried some variants of the following regex, but it is not working as I wanted.
(.*?)(\-.*)
Upvotes: 0
Views: 59
Reputation:
Something like ([^-]+?)\s*(?:-\s*(.+))?
which optionally matches
a second group started with a hyphen.
( [^-]+? ) # (1)
\s*
(?:
- \s*
( .+ ) # (2)
)?
Upvotes: 2