+ 1

Regex in Python

Does Python support recursion within regex? Is it possible to check parentheses matching in a string just in one pattern, e.g. r"..." for an arbitrarily long "(())(()(("

14th Jul 2017, 4:35 PM
yuri
9 Respuestas
+ 6
Then I am afraid it won't be doable unless you somehow combine the lazy search for the exact "\(\)" matching, lazy for "\(*\)" and greedy for "\(*\)" and the last obe as a numbered or named group to match as many as possible. Even then, though, there is a problem with "clean" (not disturbed) recurrent parenthesis, like (((()))) I can't seem to find a way for this case :/
14th Jul 2017, 9:02 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
There is a better module for this than re. It is called regex and seemingly it does support recursive search: https://pypi.python.org/pypi/regex Just use the ?R pattern. However, using regex for this purpose is still not recommended - simple parsing would be quicker and more efficient.
14th Jul 2017, 9:15 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
Are you looking for a syntax matching or just a number of opening and closing beackets being equal?
14th Jul 2017, 8:16 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
by the way, here is the (recursive) code. but I'm still looking for one line solution. https://code.sololearn.com/cesSwXg4kmt6/?ref=app
14th Jul 2017, 4:45 PM
yuri
+ 1
But you can also do it iteratively : def parenthesis(s): count=0 i=0 while count>=0 and i<len(s): if s[i]==')': count-=1 elif s[i]=='(': count+=1 i+=1 return count==0
14th Jul 2017, 5:48 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
I may be wrong but I think it is not a regular language that you are trying to check with regex, so it will not work :/
14th Jul 2017, 5:45 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
thanks, @Baptiste, I know the problem can be solved in a simple way, as you did. And my code is a mixture of re and code. again, I want to know whether it can be a line like re.findall(pattern, string) is True or False
14th Jul 2017, 6:45 PM
yuri
0
That is what I answered in my first comment. You can define the input with good parenthesis as a language (a set of word of a finite/infinite size, in our case infinite). I will not go into the details but if you can prove it is a regular language, then it can be define by a regular expression (the reciprocate is also true). And I think it is not possible
14th Jul 2017, 6:52 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
syntax matching if possible
14th Jul 2017, 8:29 PM
yuri