How to decipher :re.split(r"(\(\([^)]+\)\))" in the example
Peter Otten
__peter__ at web.de
Thu Jul 10 12:49:28 EDT 2014
fl wrote:
> Hi,
>
> This example is from the link:
>
> https://wiki.python.org/moin/RegularExpression
>
>
> I have thought about it quite a while without a clue yet. I notice that it
> uses double quote ", in contrast to ' which I see more often until now.
> It looks very complicated to me. Could you simplified it to a simple
> example?
Just break it into its components.
"(...)" in the context of re.split() keeps the delimiters while just "..."
does not. Example:
>>> re.split("a+", "abbaaababa")
['', 'bb', 'b', 'b', '']
>>> re.split("(a+)", "abbaaababa")
['', 'a', 'bb', 'aaa', 'b', 'a', 'b', 'a', '']
r"\(" matches the openening parenthesis. The "(" has to be escaped because
it otherwise has a special meaning (begin group) in a regex.
"[abc]" matches a, b, or c. A leading ^ inverts the set, so "[^abc]" matches
anything but a, b, or c. Therefore "[^)]" matches anything but the closing
parenthesis.
The complete regex then is: match two opening parens, then one or more chars
that are not closing parens, then two closing parens, and make the complete
group part of the resulting list.
PS: Note that sometimes the re.DEBUG flag may be helpful in understanding
noisy regexes:
subpattern 1
literal 40
literal 40
max_repeat 1 4294967295
not_literal 41
literal 41
literal 41
<_sre.SRE_Pattern object at 0x7f5740455c90>
> import re
> split_up = re.split(r"(\(\([^)]+\)\))",
> "This is a ((test)) of the ((emergency broadcasting
> station.))")
>
>
> ...which produces:
>
>
> ["This is a ", "((test))", " of the ", "((emergency broadcasting
> [station.))" ]
More information about the Python-list
mailing list