简体   繁体   中英

Python - Regex did not match string

I am trying to get last regex match on a message broadcast by socket, but it returns blank.

>>> msg = ':morgan.freenode.net 353 MechaBot = #xshellz :MechaBot ITechGeek zubuntu whitesn JarodRo SpeedFuse st3v0 anyx danielhyuuga1 AussieKid92 JeDa Failed Guest83885 RiXtEr xryz D-Boy warsoul buggiz rawwBNC MagixZ fedai Sunborn oatgarum dune SamUt Pythonista_ +xinfo madmattco BuGy azuan DarianC stupidpioneers AnTi_MTtr JeDaYoshi|Away PaoLo- StephenS chriscollins Rashk0 morbid1 Lord255 victorix [DS]Matej EvilSoul `|` united Scrawn avira ssnova munsterman Logxen niko gorut Jactive|OFF grauwulf b0lt saapete'
>>> r = re.compile(r"(?P<host>.*?) (?P<code>.*?) (?P<name>.*?) = (?P<msg>.*?)", re.IGNORECASE)
>>> r.search(msg).groups()
(':morgan.freenode.net', '353', 'MechaBot', '')
(?P<host>.*?) (?P<code>.*?) (?P<name>.*?) = (?P<msg>.*)

Try this.This works.See demo.Your code use .*? whch says match as few characters as you can.So while it your previous you have used .*? <space> .*? <space> it matches upto first space it encounters,in the last you have no specified anythng.So it did not match anythin as it s in lazy mode.

https://regex101.com/r/aQ3zJ3/1

You can also use

(?P<host>.*?) (?P<code>.*?) (?P<name>.*?) = (?P<msg>.*?)$

which says match lazily upto end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM