I am trying to write a regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings "(" and ")"
I expect five hundred dollars ($500).
would return
$500
Found Regular Expression to get a string between two strings in Javascript
But I'm new with regex. I don't know how to use '(', ')' in regexp
You need to create a set of escaped (with \
) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");
//matches[1] contains the value between the parentheses
console.log(matches[1]);
Breakdown:
\(
: match an opening parentheses(
: begin capturing group[^)]+
: match one or more non )
characters)
: end capturing group\)
: match closing parenthesesHere is a visual explanation on RegExplained
+1 Nice, worked like a charm. I would like to add you to add this tinyurl.com/mog7lr3 in your for a visual explanation.
@user1671639: Updated. Thanks for the link!
This doesn't work if there are parentheses within the parentheses you want to capture. Such as: "I expect five hundred dollars ($500 (but I know I'll never see that money again))."
This regex works only if matching one instance per sting. Using the global
/g
flag wont work as expected.what is the solution if you have multiple strings inside parentheses like below: "I expect (five) hundred dollars ($500)" let's say I want an array of those special strings.