简体   繁体   中英

regex re.findall

I have a string like this:

string = ' "K" -4+2-2+1+ "W" +4-1-6-8-6-4+5+ "Q" ' 

and I want to create a list with re.findall like this:

['"K"', "-4+2-2+1+", '"W"', "+4-1-6-8-6-4+5+", '"Q"']

can anyone help me on this?

You don't need regexes, you need string.split()

You can use string.split() to split around spaces in your string. Since your particular string also has trailing whitespace, I'd recommend also using string.strip() .

mystring = ' "K" -4+2-2+1+ "W" +4-1-6-8-6-4+5+ "Q" '
mylist = mystring.strip().split(" ")

mylist will have the format you need:

['"K"', '-4+2-2+1+', '"W"', '+4-1-6-8-6-4+5+', '"Q"']

If you REALLY need to do this with a Regular expression, I guess you could use an expression like this:

import re

myregex = r"(\"\w\") ([-+0-9]+) (\"\w\") ([-+0-9]+) (\"\w\")"
mystring = ' "K" -4+2-2+1+ "W" +4-1-6-8-6-4+5+ "Q" '

mylist = re.findall(myregex,mystring)

Both will result in the same list, but using strip and split will probably have better performance.

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