[英]How to get first integer between two specific characters with regex in Python?
I'm parsing some log files and need to extract a integer for a "size" parameter. 我正在解析一些日志文件,需要为“大小”参数提取一个整数。
The string (part of it) looks like this 字符串(部分)看起来像这样
"asdasdasd\\\size\\x22:22\x0A23232d:123123123\x0A2"
I want to get the first integer between ":" and "\\". 我想获取“:”和“ \\”之间的第一个整数。 That would be 22. Not 123123123.
那将是22。不是123123123。
I have tried the following code 我尝试了以下代码
p = re.compile("[\:](\d+)[\D]")
s = "asdasdasd\\size\\x22:22\x0A23232d:123123123\x0A2"
p.findall(s)[0]
output = '22'
However, if there is no number between the first appearances of ":" and "\\" and want the code to return None or 0. Right now the code will return '123123123' if the pattern looks like this: 但是,如果第一次出现的“:”和“ \\”之间没有数字,并且希望代码返回None或0。现在,如果模式如下所示,代码将返回“ 123123123”:
"asdasdasd\\size\\x22:\x0A23232d:123123123\x0A2"
What would be the best way to achieve this? 实现这一目标的最佳方法是什么?
You may use re.search
with the following pattern: 您可以按以下模式使用
re.search
:
p = re.compile(r"^[^:]*:(\d+)")
See the regex demo with String 1 and another demo with String 2 . 请参阅带有字符串1的regex演示和带有字符串2的另一个演示 。
Details 细节
^
- start of string ^
-字符串的开头 [^:]*
- 0+ chars other than :
[^:]*
-0以外的其他字符:
:
- a -
:
-一个-
(\\d+)
- Capturing group 1: one or more digits (\\d+)
-捕获组1:一位或多位数字 See the Python demo : 参见Python演示 :
import re
strs = ["asdasdasd\\size\\x22:\x0A23232d:123123123\x0A2", "asdasdasd\\\size\\x22:22\x0A23232d:123123123\x0A2"]
p = re.compile(r"^[^:]*:(\d+)")
for s in strs:
result = ""
m = p.search(s)
if m:
result = m.group(1)
else:
result = None
print(result)
Output: 输出:
None
22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.