使用regex查找任何带小数点p的数字

2024-10-02 22:32:53 发布

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

我有一个如下所示的文本文件:

15372185 ChocolateBiscuit 1.20
13281038 AppleJuice 1.50
26419633 TomatoSoup 2.10
74283187 SpringRolls 0.90

基本上,我想匹配任何有小数点的数字(这是每行的最后一个数字)。要找到开头的8位数字和描述,我有:

codes = re.findall(r'\d{8}', fread)
details = re.findall(r'\b[A-Z][a-z]*[A-Z][a-z]*', fread)

我假设我用类似的方法来找出所有带小数点的数字?我只是不明白我该怎么做。你知道吗


Tags: 方法re数字detailscodes文本文件小数点findall
2条回答

'获取要匹配的文本

Dim fileText As String = "WhereEver.txt"

'创建一个匹配字符串,包括接受像“.23”这样的数字'

Dim Reg As New Regex("(\d) (.+) (\d\.\d|\.\d)", RegexOptions.Multiline)

'获取字符串中的所有匹配项。你知道吗

Dim regMatch As MatchCollection = Reg.Matches(fileText)

'遍历每个组并获得第3项,即十进制数。你知道吗

For x = 0 To regMatch.Count - 1
    DoWhatEverYouNeedToDoWithIt()
    MsgBox(regMatch.Item(x).Groups.Item(3).Value)
Next

可以使用For[...]返回所需的值,从Item()1到3(1是8位数字,2是名称,3是小数)。或者整个团队都能得到。我的示例代码中使用了第3项。

所有代码:(测试和工作)

Dim fileText As String = "WhereEver.txt"
Dim Reg As New Regex("(\d) (.+) (\d\.\d|\.\d)", RegexOptions.Multiline)
Dim regMatch As MatchCollection = Reg.Matches(fileText)
For x = 0 To regMatch.Count - 1
    MsgBox(regMatch.Item(x).Groups.Item(3).Value)
Next
with open('test.txt', 'r') as f:
   file = f.read()
re.findall(r'\b\d+\.\d+\b', file)

结果:

['1.20', '1.50', '2.10', '0.90']

搜索小数点周围的任意数字,用边界括起来。你知道吗

如果您还需要捕获.23这样的数字,请使用:

re.findall(r'[\d+]*\.\d+', file)

相关问题 更多 >