python - 匹配多个字符串

标签 python regex

我正在学习 Python 字符串操作并尝试将分隔文本转换为变量。

“点击:20 | 瓶子:957 | jar 头:139”

此字符串应为 Tap 分配值 20,为 Bottles 分配 957,为 Cans 分配 139。此字符串不固定,可能会有所不同(例如 3 个值或 0,Tap、Bottles 或 Cans 的位置也可以互换)。

到目前为止,我已经开发了这个:

import re

strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
    print (i)
    if i.find("Bottles"):
        print("Found Bottles")
        Bottles = re.sub('[^0-9]*','',i)
        print(Bottles)
    elif i.find("Cans"):
        print("Found Cans")
        Cans = re.sub('[^0-9]*','',i)
        print(Cans)
    elif i.find("Tap"):
        print("Found Tap")
        Tap = re.sub('[^0-9]*','',i)
        print(Tap)

但是它并没有按照我的预期工作,并且每次都重新分配 Bottles 的值。

输出:

['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139']
On Tap: 20
Found Bottles
20
 Bottles: 957
Found Bottles
957
 Cans: 139
Found Bottles
139

我包含了许多 print 语句来调试代码。我的目的只是为适当的变量赋值。

最佳答案

find 在找不到字符串时返回 -1 并且 -1 被视为 True ( bool(-1) 给出 True) 所以你必须使用 find(...) != -1

import re

strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
    print (i)
    if i.find("Bottles") != -1:
        print("Found Bottles")
        Bottles = re.sub('[^0-9]*','',i)
        print(Bottles)
    elif i.find("Cans") != -1:
        print("Found Cans")
        Cans = re.sub('[^0-9]*','',i)
        print(Cans)
    elif i.find("Tap") != -1:
        print("Found Tap")
        Tap = re.sub('[^0-9]*','',i)
        print(Tap)

顺便说一句:对于您的数据,您不需要re。您可以使用split(和strip)

Bottles = i.split(':')[1].strip()

Cans = i.split(':')[1].strip()

Tap = i.split(':')[1].strip()

关于python - 匹配多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815214/

相关文章:

使用 rolling_apply 的 Python 自定义函数用于 pandas

python - 从 zip 文件中提取文件并保留 mod 日期?

javascript - 从地址字符串中提取邮政编码 - JavaScript - 英国

javascript - 如何使用正则表达式替换字符串中的所有 * 字符

javascript - 正则表达式删除/之前和之后的3个字符

python - python 表中的输出

python - 如何修复Python中的 “TypeError: string indices must be integers”错误

python - pandas python 中的 3 个月聚合和转移周期分组

regex - Bash 正则表达式检查字符串的第一个字符是否为数字

regex - Perl 正则表达式 'e' (eval) 修饰符带 s///