【问题标题】:How to match python strings similar to like in mysql如何在mysql中匹配类似于like的python字符串
【发布时间】:2018-09-14 10:07:46
【问题描述】:
a = "This is some text"
b = "This text"

我想比较a中的变量b,即使文本包含两个以上的单词,也应该返回true

a = "This is another text here"
b = "This another here"

即使我在 a 中比较 b 应该在 python 中返回 true

条件True == 找到b 中的所有单词,顺序相同,位于a
在上面的例子中,单词必须是相同的顺序和大写/小写。

【问题讨论】:

标签: python regex


【解决方案1】:
a = "This is some text"
b = "This text"

c = 0 
for i in b.split(): # check for each word in a
    if i in a: c = c + 1 # if found increases the count
c>=2 # true

len([value for value in a.split() if value in a.split()]) >= 2

【讨论】:

  • 我想要正则表达式。类似于 mysql 中的类似
【解决方案2】:

您可以使用regex 在一定程度上模仿该行为。

import re

def is_like(text,pattern):
    if '%' in pattern:
        pattern = pattern.replace('%','.*?')
    if re.match(pattern,text):
        return True
    return False


a = "This is another text here"
b = "This%another%here"
print(is_like(a,b))
>>>>True
a = "Thisis sometext"
b = "This % text"
print(is_like(a,b))
>>>>False
a = "Thisis sometext"
b = "This%text"
print(is_like(a,b))
>>>>True
a = "This is some text"
b = "This text"
print(is_like(a,b))
>>>>False

请注意,我没有对% 字符进行任何转义,因此搜索% 将不起作用。

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2020-01-04
    • 2013-01-19
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    相关资源
    最近更新 更多