简体   繁体   English

正则表达式查找特定位置的数字

[英]Regex find numbers in specific position

hi i have a string like this 嗨,我有一个像这样的字符串

track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;

i want to use some regular expression so i would end up with groups 我想使用一些正则表达式,所以我会以组结尾

pid = 1234
p1 = 21
p2 = 4343
import re

s = "track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;"

pattern = re.compile(r'.*lisen\((?P<pid>\d+),\s*(?P<p1>\d+),\s*(?P<p2>\d+)\).*')

pid, p1, p2 =  map(int, pattern.match(s).groups())

Note: I used named capturing groups, but that is not necessary in this case. 注意:我使用了命名捕获组,但是在这种情况下不是必须的。

Why regular expression? 为什么要用正则表达式? you can do it will simple string manipulations 您可以做到简单的字符串操作

>>> s="track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;"
>>> s.split("lisen(")[-1].split(")")[0].split(",")
['1234', ' 21', ' 4343']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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