而不是LIKE和〜,为什么只有SIMILAR TO才能与正则表达式匹配替代品

时间:2017-10-19 18:13:44

标签: regex postgresql

通过下面的示例,我只使用表达式SIMILAR TO获得TRUE; LIKE和〜都显示为FALSE(我猜错了吗?)

由于SIMILAR TO在很多SO帖子中都不合适,我想通过使用LIKE或〜来了解是否有一种方法可以与正则表达式匹配。

students = ("James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Donald","Mark","Paul","Steven","Andrew","Kenneth","George","Joshua","Kevin","Brian","Edward","Mary","Patricia","Jennifer","Elizabeth","Linda","Barbara","Susan","Jessica","Margaret","Sarah","Karen","Nancy","Betty","Lisa","Dorothy","Sandra","Ashley","Kimberly","Donna","Carol","Michelle","Emily","Amanda","Helen","Melissa")
print("The gold medal goes to:",students[0])
print("The silver medal goes to:",students[1])
print("The bronze medal goes to:",students[2])
print("All winners in order:")
for index, student in enumerate(students in range(3,51)):
    place=str(index+1)
    print(place,student.title())

2 个答案:

答案 0 :(得分:5)

LIKE支持使用_对任何单个字符进行模式匹配,并为任何字符序列支持%,这样:

SELECT 'thomas' LIKE '%(h|x)%'

不起作用,因为LIKE不理解(...)进行分组或|进行更改,这些只是LIKE模式中的文字字符。

SIMILAR TO支持_%与LIKE相同,但添加(...)分组,与|交替,以及其他一些内容,以便:

SELECT 'thomas' SIMILAR TO '%(h|x)%'

按预期工作。

~*使用POSIX正则表达式,因此(...)用于分组,|用于替换,但%只是百分号;这意味着:

SELECT 'thomas' ~* '%(h|x)%'

正在寻找被百分号包围的hx,并且按预期方式无法正常工作。

如果您使用正确的正则表达式,则~*版本将起作用:

SELECT 'thomas' ~* '(h|x)' -- alternation
SELECT 'thomas' ~* 'h|x'   -- alternation without an unnecessary grouping
SELECT 'thomas' ~* '[hx]'  -- or a character class

上面链接的文档涵盖了所有这些内容。

答案 1 :(得分:0)

在这种情况下你可以使用〜*:

SELECT 'thomas' ~* '.*(h|x).*'

SELECT 'thomas' ~* 'h|x'

请注意,您应该使用〜,〜*运算符使用POSIX正则表达式语法。