2017-03-10 17:52:36 +00:00
|
|
|
#pragma once
|
|
|
|
|
2021-10-02 07:13:14 +00:00
|
|
|
#include <base/types.h>
|
2017-03-10 17:52:36 +00:00
|
|
|
|
|
|
|
namespace DB
|
|
|
|
{
|
2020-07-05 15:57:59 +00:00
|
|
|
|
|
|
|
/// Transforms the [I]LIKE expression into regexp re2. For example, abc%def -> ^abc.*def$
|
2022-05-24 19:29:43 +00:00
|
|
|
inline String likePatternToRegexp(std::string_view pattern)
|
2017-03-10 17:52:36 +00:00
|
|
|
{
|
2017-04-01 07:20:54 +00:00
|
|
|
String res;
|
|
|
|
res.reserve(pattern.size() * 2);
|
|
|
|
const char * pos = pattern.data();
|
|
|
|
const char * end = pos + pattern.size();
|
2017-03-10 17:52:36 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
if (pos < end && *pos == '%')
|
|
|
|
++pos;
|
|
|
|
else
|
|
|
|
res = "^";
|
2017-03-10 17:52:36 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
while (pos < end)
|
|
|
|
{
|
|
|
|
switch (*pos)
|
|
|
|
{
|
|
|
|
case '^': case '$': case '.': case '[': case '|': case '(': case ')': case '?': case '*': case '+': case '{':
|
|
|
|
res += '\\';
|
|
|
|
res += *pos;
|
|
|
|
break;
|
|
|
|
case '%':
|
|
|
|
if (pos + 1 != end)
|
|
|
|
res += ".*";
|
|
|
|
else
|
|
|
|
return res;
|
|
|
|
break;
|
|
|
|
case '_':
|
|
|
|
res += ".";
|
|
|
|
break;
|
|
|
|
case '\\':
|
2021-04-25 00:58:44 +00:00
|
|
|
/// Known escape sequences.
|
|
|
|
if (pos + 1 != end && (pos[1] == '%' || pos[1] == '_'))
|
|
|
|
{
|
|
|
|
res += pos[1];
|
|
|
|
++pos;
|
|
|
|
}
|
|
|
|
else if (pos + 1 != end && pos[1] == '\\')
|
|
|
|
{
|
2017-04-01 07:20:54 +00:00
|
|
|
res += "\\\\";
|
2021-04-25 00:58:44 +00:00
|
|
|
++pos;
|
|
|
|
}
|
2017-04-01 07:20:54 +00:00
|
|
|
else
|
|
|
|
{
|
2021-04-25 00:58:44 +00:00
|
|
|
/// Unknown escape sequence treated literally: as backslash and the following character.
|
|
|
|
res += "\\\\";
|
2017-04-01 07:20:54 +00:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
res += *pos;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
++pos;
|
|
|
|
}
|
2017-03-10 17:52:36 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
res += '$';
|
|
|
|
return res;
|
2017-03-10 17:52:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|