1#pragma once
2
3#include <Core/Types.h>
4
5namespace DB
6{
7/// Transforms the LIKE expression into regexp re2. For example, abc%def -> ^abc.*def$
8inline String likePatternToRegexp(const String & pattern)
9{
10 String res;
11 res.reserve(pattern.size() * 2);
12 const char * pos = pattern.data();
13 const char * end = pos + pattern.size();
14
15 if (pos < end && *pos == '%')
16 ++pos;
17 else
18 res = "^";
19
20 while (pos < end)
21 {
22 switch (*pos)
23 {
24 case '^': case '$': case '.': case '[': case '|': case '(': case ')': case '?': case '*': case '+': case '{':
25 res += '\\';
26 res += *pos;
27 break;
28 case '%':
29 if (pos + 1 != end)
30 res += ".*";
31 else
32 return res;
33 break;
34 case '_':
35 res += ".";
36 break;
37 case '\\':
38 ++pos;
39 if (pos == end)
40 res += "\\\\";
41 else
42 {
43 if (*pos == '%' || *pos == '_')
44 res += *pos;
45 else
46 {
47 res += '\\';
48 res += *pos;
49 }
50 }
51 break;
52 default:
53 res += *pos;
54 break;
55 }
56 ++pos;
57 }
58
59 res += '$';
60 return res;
61}
62
63}
64