python - 检查字符串的特定格式的子字符串,如何..?

标签 python regex string compare substring

两个字符串。我的元素名称:

Parfume name EDT 50ml

和竞争对手的项目名称:

Parfume another name EDP 60ml

我在一列中列出了一长串这些名称,在另一列中列出了竞争对手的名称,我只想在数据框中保留那些行,无论其他什么,我和竞争对手的名称中都具有相同数量的 ml在这些字符串中看起来像。那么如何在更大的字符串中找到以“ml”结尾的子字符串呢?我可以简单地做

competitors_name 中的“**ml”

看看它们是否含有相同数量的 ml。

谢谢

更新

'ml' 并不总是在字符串的末尾。它可能看起来像这样

Parfume yet another great name 60ml EDP

最佳答案

试试这个:

import re

def same_measurement(my_item, competitor_item, unit="ml"):
    matcher = re.compile(r".*?(\d+){}".format(unit))
    my_match = matcher.match(my_item)
    competitor_match = matcher.match(competitor_item)
    return my_match and competitor_match and my_match.group(1) == competitor_match.group(1)

my_item = "Parfume name EDT 50ml"
competitor_item = "Parfume another name EDP 50ml"
assert same_measurement(my_item, competitor_item)

my_item = "Parfume name EDT 50ml"
competitor_item = "Parfume another name EDP 60ml"
assert not same_measurement(my_item, competitor_item)

关于python - 检查字符串的特定格式的子字符串,如何..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743840/

相关文章:

python - 使用 python 访问 Chrome DOM 树

用于使用 preg_replace_callback 评估 html 的 if/else 条件的 PHP 正则表达式模式

c - 替换字符串中的字符

时间:2019-03-17 标签:c#string.length

python - 使用 bash 而不是 sh 作为 python 命令命名空间函数的首选 shell

python - Odoo错误: TypeError: 'int' object is not iterable

python - 相机标定Opencv-Python

python - 在正则表达式中如何将字母数字字符串的模式与它们之前/之后的空格或标点符号匹配

javascript - 如何找到特定的模式?

javascript - localStorage的返回类型是什么?