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
Ported Mr_Green's answer to a functional programming style to avoid use of temporary global variables.
Try string manipulation:
or regex (which is somewhat slow compare to the above)
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: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
For just digits after a currency sign :
\(.+\s*\d+\s*\)
should workOr
\(.+\)
for anything inside bracketsTo match a substring inside parentheses excluding any inner parentheses you may use
pattern. See the regex demo.
In JavaScript, use it like
Pattern details
\(
- a(
char([^()]*)
- Capturing group 1: a negated character class matching any 0 or more chars other than(
and)
\)
- a)
char.To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value:
Simple solution
Notice: this solution used for string that has only single "(" and ")" like string in this question.
Online demo (jsfiddle)