匹配数据库中的通配符表达式?

时间:2022-09-01 22:59:51

Given an input string, I'd like to return the rows from a (MySQL) database that contain a wildcard expression that would match the string. For example, if I have a table containing these wildcard expressions:

给定一个输入字符串,我希望返回包含匹配字符串的通配符表达式的(MySQL)数据库中的行。例如,如果我有一个包含这些通配符表达式的表:

foo.*
foo.bar.*
erg.foo.*

and my input string is "foo.bar.baz", then I should get the rows "foo.*" and "foo.bar.*".

我的输入字符串是"foo.bar "baz,然后我应该得到行。*”和“foo.bar。*”。

Any ideas on how this can be implemented? I'm hoping it can be accomplished with a query, but I might have to select all relevant rows and do the matching in the application.

关于如何实现这一点有什么想法吗?我希望它可以通过查询来完成,但是我可能必须选择所有相关的行并在应用程序中进行匹配。

1 个解决方案

#1


3  

SELECT  *
FROM    mytable
WHERE   'foo.bar.baz' RLIKE match

You are not limited to the wildcards and can use any regular expression MySQL supports.

您不仅可以使用通配符,还可以使用任何MySQL支持的正则表达式。

However, if you only want to process asterisk wildcards, you may use this syntax:

但是,如果您只想处理星号通配符,可以使用以下语法:

SELECT  *
FROM    mytable
WHERE   'foo.bar.baz' LIKE REPLACE(REPLACE(REPLACE(REPLACE('\\', '\\\\'), '.', '\\.'), '%', '\\%'), '*', '%') ESCAPE '\\'

#1


3  

SELECT  *
FROM    mytable
WHERE   'foo.bar.baz' RLIKE match

You are not limited to the wildcards and can use any regular expression MySQL supports.

您不仅可以使用通配符,还可以使用任何MySQL支持的正则表达式。

However, if you only want to process asterisk wildcards, you may use this syntax:

但是,如果您只想处理星号通配符,可以使用以下语法:

SELECT  *
FROM    mytable
WHERE   'foo.bar.baz' LIKE REPLACE(REPLACE(REPLACE(REPLACE('\\', '\\\\'), '.', '\\.'), '%', '\\%'), '*', '%') ESCAPE '\\'