简体   繁体   中英

How to use in python regular expression

I would like to use a numeric variable regular expression part.

What should I do if I want to use a variable in this part (?P<hh>\\d)

I want to output lines that contain the input number.

Your question isn't clear.

If you want to capture some specific part of the regex , you have to create groups (using pharentesis):

hh = sys.argv[1]
m = re.compile(r'(?P<hh>\d):(\d{2})')
match = m.match(hh)

print match.group(1)
print match.group(2)

for example, if hh = '1:23' , the above code will print:

1
23


Now, if what you need is replace \\d{2} by some variable , you can do:

variable = r'\d{2}'
m = re.compile(r'(?P<hh>\d):%s' % variable)

or if you just want to replace the 2 , you can do:

variable = '2'
m = re.compile(r'(?P<hh>\d):\d{%s}' % variable)

Another option could be using:

r'(?P<hh>\d):{0}'.format(variable)

Using string interpolation :

m = re.compile(r'\d{%d}:\d{%d}' % (var1, var2))

If the vars aren't already integers you may need to convert types like so:

m = re.compile(r'\d{%d}:\d{%d}' % (int(var1), int(var2)))

你可以把它作为一个字符串传递(我先逃避它):

m = re.compile(re.escape(hh) + r':\d{2}')

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