I am new to learning regex in python and I'm wondering how do I use regex in python to store the integers(positive and negative) i want into a list!
For example
This is the data in a list.
data =
[u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=-5,B=5)',
u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=5,Y=5)',
u'\x1b[0m[\x1b[1m\x1b[10m\xbb\x1b[0m\x1b[36m]\x1b[0m : ']
How do I extract the integer values of A and B (negative and positive) and store them in a variable so that I can work with the numbers?
I tried smth like this but the list is empty ..
for line in data[0]:
pattern = re.compile("([A-Z]=(-?\d+?),[A-Z]=(-?\d+?))")
store = pattern.findall(line)
print store
Thank you and appreciate it
For a positive and negative integer, with or without commas in between use: -?(?:\\d+,?)+
-?
with or without negative sign(?:
opens a group \\d+
one or more digits ,?
optional comma)
closes the group (?:\\d+,?)+
this group may have one or then one occencences
Depending on what you are trying to accomplish, this may work:
import re
data = [
u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=-5,B=5)',
u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=5,Y=5)',
u'\x1b[0m[\x1b[1m\x1b[10m\xbb\x1b[0m\x1b[36m]\x1b[0m : '
]
for line in data:
m = re.search('\((\w)=(-?\d+),(\w)=(-?\d+)\)', line)
if not m:
continue
myvars = {}
myvars[m.group(1)] = int(m.group(2))
myvars[m.group(3)] = int(m.group(4))
print myvars
This results in a dictionary ( myvars
) containing the variables in the current line. If you use this, you will have to check that the variable you want is defined before you attempt to get it from the dictionary. The output of the above is:
{u'A': -5, u'B': 5}
{u'A': 5, u'Y': 5}
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.