0

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.

4

3 回答 3

1

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

于 2013-09-13T02:36:11.803 回答
0

我没有看到任何嵌套在那里。嵌套意味着这样的事情:

12 (34 (56) 78) 90

如果你真的有这样的数据——特别是如果你不知道嵌套可以有多深——我建议你不要使用正则表达式。但是你的问题看起来很简单;这应该是你所需要的:

\d+(?=[^()]*\))

与其他答案一样,前瞻断言前面有右括号,这里和那里之间没有左括号。我也排除了右括号,主要是为了提高效率。否则它会倾向于放大过去),只需要回溯到它。

于 2013-09-14T01:21:25.587 回答
0

在此处使用此模式\d+(?=(((?!\().)*)\))示例

修改为如下(\d+)(?=(?:(?!\().)*\)) demo

于 2013-09-13T02:43:15.860 回答