Yang
Yang

Reputation: 6892

Regex Match Groups with or with out "-"

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

Answers (2)

m87
m87

Reputation: 4523

The following regex should do it ...

([\w\s]+)(?:[\s-]?)(.*?)(?:\n|$)

see regex demo / explanation

Upvotes: 1

user557597
user557597

Reputation:

Something like ([^-]+?)\s*(?:-\s*(.+))? which optionally matches
a second group started with a hyphen.

 ( [^-]+? )                    # (1)
 \s* 
 (?:
      - \s* 
      ( .+ )                        # (2)
 )?

Upvotes: 2

Related Questions