Reputation:
I am trying to find and capture all numbers inside ( and ) separately in my data, ignoring the rest of the numbers.
My data looks like this
21 [42] (12) 19 25 [44] (25 26 27) 17 (14 3) 8 1 6 (19)
So I want to find matches for 12
, 25
, 26
, 27
, 14
, 3
and 19
I tried doing \((\d+)\)*
but this only gives me 12
, 25
, 14
, 19
Any help is appreciated.
Upvotes: 0
Views: 63
Reputation: 75222
I don't see any nesting there. Nesting implies something like this:
12 (34 (56) 78) 90
If you really have data like that--especially if you don't know how deep the nesting can go--I would advise you not to use regexes. But your problem looks very simple; this should be all you need:
\d+(?=[^()]*\))
As with the other answers, the lookahead asserts that there's closing bracket up ahead, with no opening brackets between here and there. I excluded closing brackets too, mostly for the sake of efficiency. Otherwise it would tend to zoom on past the )
at first, only to have to backtrack to it.
Upvotes: 0
Reputation: 7948
use this pattern \d+(?=(((?!\().)*)\))
example here
modified to the following (\d+)(?=(?:(?!\().)*\))
demo
Upvotes: 0
Reputation: 70722
You can combine a positive lookahead with a negative lookahead to get your desired results.
(\d+)(?=(?:.(?!\())*\))
Regular expression:
( group and capture to \1:
\d+ digits (0-9) (1 or more times)
) end of \1
(?= look ahead to see if there is:
(?: group, but do not capture (0 or more times)
. any character except \n
(?! look ahead to see if there is not:
\( '('
) end of look-ahead
)* end of grouping
\) ')'
) end of look-ahead
See a demo
Upvotes: 1