如何从字符串中提取第一组整数?

2024-06-16 11:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从字符串中提取#旁边的数字:ackCount。 我正在使用索引,但哈希旁边的位数可能会增加到5或6…以此类推。 我能否只获取紧跟在#之后的数字(而不是字符串最后的1) 下面是获取4位数字的临时代码

ackCount = "Acknowledgement of  #2352 on component \"lOrA-1\""
OAC = int(re.sub("\\D", "", ackCount)[0:4])
print(OAC)

Tags: of字符串代码reon数字componentint
3条回答

如果字符串始终相同,则可以使用ackCount = ackCount.split()

这将返回一个列表,其中每个元素都是原始字符串中的一个单词。默认情况下split()使用空格作为分隔符

然后使用ackCount[2][1:]获取所有数字,再次假设它是相同的常规字符串,但只是数字不同。所以,索引列表的2,然后是从索引1开始的字符串的所有字符(因为字符串的索引0是“#”)

为此,可以使用正则表达式。确保你做出了正确的图案!以下内容将返回所有匹配项的列表:

import re
string = "he hallo #9090 8080 fdsf sfd222 f222"
find = re.findall("(?<=#)[0-9]+\\b", string)
print(find)

输出:['9090']

字符串string = "he hallo #9090 8080 fdsf sfd222 f222 #888"将返回['9090', '888']

re.search(r"#(\d+)", ackCount).group(1)

这将在ackCount字符串中搜索第一个出现的八进制('#'),后跟一个或多个(+)数字(\d),仅捕获由re.search()返回的Match对象的捕获组(.group(1))中的数字

就你的问题而言,这将成为:

ackCount = "Acknowledgement of  #2352 on component \"lOrA-1\""
try:
    OAC = int(re.search(r"#(\d+)", ackCount).group(1))
    print(OAC)
# error handling if the cast to `int` fails, or there is no returned match
except ValueError, AttributeError:
    print("No match found.")
>>> 2352

相关问题 更多 >