Reputation: 1689
From a string:
"(book(1:3000))"
I need to exclude opening and closing brackets and match:
"book(1:3000)"
using regular expression.
I tried this regular expression:
/([^',()]+)|'([^']*)'/
which detects all characters and integers excluding brackets. The string detected by this regex is:
"book 1:3000"
Is there any regex that disregards the opening and closing brackets, and gives the entire string?
Upvotes: 0
Views: 1769
Reputation: 6041
"(book(1:3000))"[/^\(?(.+?\))\)?/, 1]
=> "book(1:3000)"
"book(1:3000)"[/^\(?(.+?\))\)?/, 1]
=> "book(1:3000)"
The regex split on multiple lines for easier reading:
/
^ # start of string
\(? # character (, possibly (?)
( # start capturing
.+? # any characters forward until..
\) # ..a closing bracket
) # stop capturing
/x # end regex with /x modifier (allows splitting to lines)
1. Look for a possible (
in the beginning of string and ignore it.
2. Start capturing
3. Capture until and including the first )
But this is where it fails:
"book(1:(10*30))"[/^\(?(.+?\))\)?/, 1]
=> "book(1:(10*30)"
If you need something like that, you probably need to use a recursive regex as described in another stackoverflow answer.
Upvotes: 2
Reputation: 121010
Build the regexp that explicitly states exactly what you want to extract: alphanumerics, followed by the opening parenthesis, followed by digits, followed by a colon, followed by digits, followed by closing parenthesis:
'(book(1:3000))'[/\w+\(\d+:\d+\)/]
#⇒ "book(1:3000)"
Upvotes: 2