[英]How to get specific digits only after a word Python regex?
我有一个这样的字符串:
'$."result"."000182"."200"', '$."result"."000490"."200"', '$."result"."000530"."200"'
我想在之后得到一个数字结果的数组
"result"."[WANTOGETTHISNUMBER]"."200"
我试过这样的(例子)
test_str = "'$.""result"".""000109"".""200""', '$.""result"".""000110"".""200""', '$.""result"".""000111"".""200""', '$.""result"".""000112"".""200""'"
x = re.findall('[0-9]+', test_str)
print(x)
#['000109', '200', '000110', '200', '000111', '200', '000112', '200']
但我希望 output 为: ['000109', '000110', '000111', '000112']
实现这一目标的正确方法是什么?
您可以使用此正则表达式:
>>> re.findall('result\.([0-9]+)', test_str)
['000109', '000110', '000111', '000112']
这是一个将过多引号考虑在内的正则表达式:
test_str = """ '$.""result"".""000109"".""200""', '$.""result"".""000110"".""200""', '$.""result"".""000111"".""200""', '$.""result"".""000112"".""200""'" """
re.findall(r"result\"\".\"\"(\d+)", test_str)
结果是:
['000109', '000110', '000111', '000112']
在字符串中查找特定长度的数字
要查找特定长度的数字 N 是一个字符串,请使用正则表达式 [0-9]+ 查找任意长度的数字字符串。 [0-9] 匹配单个数字。 找到所有项目后,使用指定的长度过滤它们。
示例 1:在字符串中查找特定长度的数字
在下面的示例中,我们获取一个字符串,并在该字符串中找到所有 3 位数字。
Python 程序
` import res tr = """我们四个人,住在 Malibeu 521 的第 2 街。我口袋里有 248 美元现金。我得到了一张序列号为 88796451-52 的票。""" #search using regex x = re.findall('[0-9]+', str) print('All Numbers\n',x) #digits of length NN=3 def filterNumber(n): if(len(n)==N) :
否则返回真:
返回假
#过滤列表 finalx = list(filter(filterNumber, x)) print('Final List\n',finalx)
Output
All Numbers ['2', '521', '248', '88796451', '52'].
Final List ['521', '248']`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.