Reputation: 2550
I have a string that can look like either of these Adjuster, Carrier 3 (Carrier 3)
or Adjuster, Carrier 3 (Carrier 3 (Test))
I want to capture the contents within the first set of parentheses. My original regex pattern was \((.+?)\)
(non-greedy), so I can capture the text as group #1.
var selectedOwnerText = /* GET THE TEXT FROM NODE/FIELD/ETC. */,
carrierName = '',
rePattern = /\((.+?)\)/;
if (selectedOwnerText != '') {
carrierName = selectedOwnerText.match(rePattern);
if (carrierName != null) {
carrierName = carrierName[1];
}
}
// Rest of code...
This works in the first text case, but in the second text case it grabs the outer parentheses e.g. (Carrier 3 (Test)
.
Is there a regex pattern that can capture the text inside the outer parentheses, which may include parentheses as well? I want either Carrier 3
or Carrier 3 (Test)
extracted from the above.
EDIT: I have just been told that this data field is free-form text, so anything could appear inside the outer parentheses. So, I would need to capture everything inside the outer parentheses.
EDIT 2: I gave one user the correct answer, because it answered the original question (assuming only one set of inner parentheses). Now that I know the text could be anything, a Javascript regex pattern is impossible, and I abandoned the regex approach. I dived into the server-side code and surfaced a JSON literal of the data I needed, so as the page/Javascript is being created, I can use the data structure to get the content I need without worrying about what the string actually looks like. Thanks to all who tried to help!
Upvotes: 0
Views: 403
Reputation: 71538
You can just use the greedy version if and only if your string has the format word, word (anything inside)
and not word, word (anything inside) word (more parenthesized stuff)
:
/\((.+)\)/;
You'll get everything within the first opening parenthesis and the last closing parenthesis.
Upvotes: 1