Reputation: 906
I am trying to match a string for two cases by a single regular expressing in JavaScript. The string can be in any one of the given formats
//Singapore
//Singapore (country)
I have tried the following regular expression to match the strings
"singapore".match(/(.*) (?:\((.*)\))?/)
//null
"singapore (country)".match(/(.*) (?:\((.*)\))?/)
//["singapore (country)", "singapore", "country"]
I want both the results to return an array like the 2nd case where the 3rd entry in the array can be undefined/empty or not present at all but the result should not be null.
Can this be done by a single regular expression. If yes then what is the mistake in the above expression
Upvotes: 0
Views: 105
Reputation: 382122
You need to put the space in the optional group, because it's not here in the case of just "singapore"
: /^([^\(]*)(?: \(([^\)]*)\))?$/
Upvotes: 4