Alex Edwards
Alex Edwards

Reputation: 1673

Can i remove the OR from this regex

I have this regex

((.*?)(\(.*?\))|(.*?)) 

I would like to remove the | as i think there is a better way of matching this. Here are some example strings that I would like it to match

myString

myString(1234)

if it has brackets I want to capture the contents of the brackets as a separate capture group. It never has to capture both types of string.

Upvotes: 1

Views: 46

Answers (2)

Kendall Frey
Kendall Frey

Reputation: 44336

Just use

.*?(\(.*?\))?

This makes the bracketed part optional, and the first .*? will match everything if the bracketed part isn't there.

Upvotes: 0

codaddict
codaddict

Reputation: 455142

As the (...) part is optional, you can make the sub-regex which matches it optional as well:

((.*?)(\(.*?\))?)  

Upvotes: 3

Related Questions