Please advise on the Python regular expression

Viewed 40
message = <@U0104FGR7SL> test111 <@U0106LSJ> test33

There is the above string.

Based on the reference letter corresponding to the pattern <@U......>

I'd like to split the text.

I'd like to cut it by a pattern.

regex = re.compile("<@U[^>]+>")

match = regex.split (message)

If I do this, I get a "test, test22"

<@U0104FGR7SL> test111 
<@U0106LSJ> test33

I'd like to split it this way.

Please advise me what to do.

3 Answers

You can do the following:

import re
message = "<@U0104FGR7SL> test111 <@U0106LSJ> test33"
matches = re.findall("<\S+>\s\S+", message)
for x in matches:
    print(x)
# <@U0104FGR7SL> test111
# <@U0106LSJ> test33

Another one - using the newer regex module which supports splitting by lookarounds:

import regex as re

string = "<@U0104FGR7SL> test111 <@U0106LSJ> test33"
parts = re.split(r'(?<!\A)(?=<@)', string)
print(parts)

This yields

['<@U0104FGR7SL> test111 ', '<@U0106LSJ> test33']

See a demo on regex101.com.

You may use either of the two re.split solutions:

re.split(r'\s+(?=<@U[^>]+>)', message)    # Any Python version, if matches are whitespace separated
[x.strip() for x in re.split(r'(?=<@U[^>]+>)', message) if x] # Starting with Python 3.7

NOTE: In Python 3.7, re.split finally was fixed to split with empty matches.

Details

  • \s+ - 1+ whitespaces
  • (?=<@U[^>]+>) - a positive lookahead that requires <@U, 1+ chars other than > and then > immediately to the right of the current location.

See the Python demo:

import re
message = '<@U0104FGR7SL> test111 <@U0106LSJ> test33'
print ( re.split(r'\s+(?=<@U[^>]+>)', message) )
# => '<@U0104FGR7SL> test111', '<@U0106LSJ> test33']
print ( [x.strip() for x in re.split(r'(?=<@U[^>]+>)', message) if x] )
# => '<@U0104FGR7SL> test111', '<@U0106LSJ> test33']
Related