How to decipher :re.split(r"(\(\([^)]+\)\))" in the example

MRAB python at mrabarnett.plus.com
Thu Jul 10 19:01:18 CEST 2014


On 2014-07-10 16:37, 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?
>
>
> Thanks,
>
>
>
>
>
> 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.))" ]
>
No it doesn't; you've omitted the final string.

The regex means:

(        Start of capture group.
\(       Literal "(".
\(       Literal "(".
[^)]+    One or more repeats of any character except a literal ")".
\)       Literal ")".
\)       Literal ")".
)        End of capture group.

.split returns a list of the parts of the string between the matches, 
and if, as in this example, there are capture groups, then those too:

[
'This is a ',                             # The part before the first
                                           # match.
'((test))',                               # The first match (group 1).
' of the ',                               # The part between the first
                                           # and second matches.
'((emergency broadcasting station.))',    # The second match.
''                                        # The part after the second
                                           # match.
]




More information about the Python-list mailing list