Regex: match braces to both greedy and non-greedy

I use a regular expression module for python, re.

I need to match something inside '(' ')' on these two phrases, but "not so greedy." Like this:

show the (name) of the (person)

calc the sqrt of (+ (* (2 4) 3))

The result should be returned from phrase 1:

name
person

The result should return from phrase 2:

+ (* (2 4) 3)

The problem is that, to match the first sentence, I used '\(.*?\)'

This, in the second sentence, just fits + (* (2 4)

And using the '\(.*\)'second phrase for the correct installation, the first phrase is suitable(name) of the (person)

Does regular expression work on both phrases correctly?

+5
source share
4 answers

Pyparsing :

>>> text = """show the (name) of the (person)
...
... calc the sqrt of (+ (* (2 4) 3))"""
>>> import pyparsing
>>> for match in pyparsing.nestedExpr('(',')').searchString(text):
...   print match[0]
...
['name']
['person']
['+', ['*', ['2', '4'], '3']]

, , .

, originalTextFor:

>>> for match in pyparsing.originalTextFor(pyparsing.nestedExpr('(',')')).searchString(text):
...   print match[0]
...
(name)
(person)
(+ (* (2 4) 3))
+6

, , ( LISP, , , PyLisp out). .

. , @wikipedia Python .

0

:

(?:\()(.*?\){2})|(?:\()(.*?)(?:\))

1 = + (* (2 4) 3)

  • The last ")" can be removed with .strip (')')

Group 2 = name , person

0
source

As long as the brackets are not nested, you can use a lazy regular expression:

\(.*?\)

While you can theoretically parse a limited number of nests in regular terms, this is very difficult and not worth the effort. This is much easier to do using the python custom function. See this answer for a good explanation.

-3
source

All Articles