-
Notifications
You must be signed in to change notification settings - Fork 6
/
regex.ex
293 lines (213 loc) · 7.25 KB
/
regex.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
defmodule Unicode.Regex do
@moduledoc """
Implements [Unicode regular expressions](http://unicode.org/reports/tr18/)
by transforming them into regular expressions supported by
the Elixir Regex module.
"""
@default_options "u"
defguard is_perl_set(c) when c in ["p", "P"]
@doc """
Compiles a binary regular expression after
expanding any Unicode Sets.
## Arguments
* `string` is a regular expression in
string form
* `options` is a string or a list which is
passed unchanged to `Regex.compile/2`.
The default is "u" meaning the regular
expression will operate in Unicode mode
## Returns
* `{:ok, regex}` or
* `{:error, {message, index}}`
## Notes
This function operates by splitting the string
at the boundaries of Unicode Set markers which
are:
* Posix style: `[:` and `:]`
* Perl style: `\\p{` and `}`
This parsing is naive meaning that is does not
take any character escaping into account when s
plitting the string.
## Example
iex> Unicode.Regex.compile("[:Zs:]")
{:ok, ~r/[\\x{20}\\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{202F}\\x{205F}\\x{3000}]/u}
iex> Unicode.Regex.compile("\\\\p{Zs}")
{:ok, ~r/[\\x{20}\\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{202F}\\x{205F}\\x{3000}]/u}
iex> Unicode.Regex.compile("[:ZZZZ:]")
{:error, {'POSIX named classes are supported only within a class', 0}}
"""
def compile(string, options \\ @default_options) do
options = force_unicode_option(options)
string
|> split_character_classes
|> expand_unicode_sets
|> Enum.join()
|> Regex.compile(options)
end
@doc """
Compiles a binary regular expression after
interpolating any Unicode Sets.
## Arguments
* `string` is a regular expression in
string form.
* `options` is a string or a list which is
passed unchanged to `Regex.compile/2`.
The default is "u" meaning the regular
expression will operate in Unicode mode
## Returns
* `regex` or
* raises an exception
## Example
iex> Unicode.Regex.compile!("[:Zs:]")
~r/[\\x{20}\\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{202F}\\x{205F}\\x{3000}]/u
"""
def compile!(string, opts \\ @default_options) do
case compile(string, opts) do
{:ok, regex} -> regex
{:error, {message, index}} -> raise(Regex.CompileError, "#{message} at position #{index}")
end
end
@doc """
Returns a boolean indicating whether there was a match or not
with a Unicode Set.
## Arguments
* `regex_string` is a regular expression in
string form.
* `string` is any string against which
the regex match is executed
* `options` is a string or a list which is
passed unchanged to `Regex.compile/2`.
The default is "u" meaning the regular
expression will operate in Unicode mode
## Returns
* a boolean indicating if there was a match or
* raises an exception if `regex` is not
a valid regular expression.
## Example
iex> Unicode.Regex.match?("[:Sc:]", "$")
true
"""
def match?(regex_string, string, opts \\ @default_options)
def match?(regex_string, string, opts) when is_binary(regex_string) do
regex = compile!(regex_string, opts)
Regex.match?(regex, string)
end
def match?(%Regex{} = regex, string, _opts) do
Regex.match?(regex, string)
end
@doc """
Split a regex into character classes
so that these can then be later compiled.
## Arguments
* `string` is a regular expression in
string form.
## Returns
* A list of string split at the
boundaries of unicode sets
## Example
iex> Unicode.Regex.split_character_classes("This is [:Zs:] and more")
["This is ", "[:Zs:]", " and more"]
"""
def split_character_classes(string) do
string
|> split_character_classes([""])
|> Enum.reverse()
end
defp split_character_classes("", acc) do
acc
end
defp split_character_classes(<<"\\p{", rest::binary>>, acc) do
split_character_classes(rest, ["\\p{" | acc])
end
defp split_character_classes(<<"\\P{", rest::binary>>, acc) do
split_character_classes(rest, ["\\P{" | acc])
end
defp split_character_classes(<<"\\", char::binary-1, rest::binary>>, [head | others]) do
split_character_classes(rest, [head <> "\\" <> char | others])
end
defp split_character_classes(<<"[", _rest::binary>> = string, acc) do
{character_class, rest} = extract_character_class(string)
split_character_classes(rest, ["" | [character_class | acc]])
end
perl_set =
quote do
[<<"\\", var!(c)::binary-1, var!(head)::binary>> | var!(others)]
end
defp split_character_classes(<<"}", rest::binary>>, unquote(perl_set)) when is_perl_set(c) do
split_character_classes(rest, ["" | ["\\" <> c <> head <> "}" | others]])
end
defp split_character_classes(<<"]", rest::binary>>, [head | others]) do
split_character_classes(rest, ["" | [head <> "]" | others]])
end
defp split_character_classes(<<char::binary-1, rest::binary>>, [head | others]) do
split_character_classes(rest, [head <> char | others])
end
# Extract a character class which may be
# arbitrarily nested
defp extract_character_class(string, level \\ 0)
defp extract_character_class("" = string, _level) do
{string, ""}
end
defp extract_character_class(<<"\\[", rest::binary>>, level) do
{string, rest} = extract_character_class(rest, level)
{"\\[" <> string, rest}
end
defp extract_character_class(<<"\\]", rest::binary>>, level) do
{string, rest} = extract_character_class(rest, level)
{"\\]" <> string, rest}
end
defp extract_character_class(<<"[", rest::binary>>, level) do
{string, rest} = extract_character_class(rest, level + 1)
{"[" <> string, rest}
end
defp extract_character_class(<<"]", rest::binary>>, 1) do
{"]", rest}
end
defp extract_character_class(<<"]", rest::binary>>, level) do
{string, rest} = extract_character_class(rest, level - 1)
{"]" <> string, rest}
end
defp extract_character_class(<<char::binary-1, rest::binary>>, level) do
{string, rest} = extract_character_class(rest, level)
{char <> string, rest}
end
# Expand unicode sets to their codepoints
defp expand_unicode_sets([<<"[", set::binary>> | rest]) do
regex = "[" <> set
case Unicode.Set.to_regex_string(regex) do
{:ok, string} -> [string | expand_unicode_sets(rest)]
{:error, _} -> [regex | expand_unicode_sets(rest)]
end
end
defp expand_unicode_sets([<<"\\", c::binary-1, set::binary>> | rest]) when is_perl_set(c) do
regex = "\\" <> c <> set
case Unicode.Set.to_regex_string(regex) do
{:ok, string} -> [string | expand_unicode_sets(rest)]
{:error, _} -> [regex | expand_unicode_sets(rest)]
end
end
defp expand_unicode_sets(["" | rest]) do
expand_unicode_sets(rest)
end
defp expand_unicode_sets([head | rest]) do
[head | expand_unicode_sets(rest)]
end
defp expand_unicode_sets([]) do
[]
end
# Always use the unicode option on the regex
defp force_unicode_option(options) when is_binary(options) do
if String.contains?(options, "u") do
options
else
options <> "u"
end
end
defp force_unicode_option(options) when is_list(options) do
if Enum.find(options, &(&1 == :unicode)) do
options
else
[:unicode | options]
end
end
end