regexes 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,254 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # A regular expression with the variations every expression allows: anchored at the start or end of the text
5
+ # ({#leading}, {#trailing}, {#whole}) or of a line ({#line_leading}, {#line_trailing}, {#whole_line});
6
+ # repeated ({#one_or_more}, {#zero_or_more}, {#optional}, {#exactly}, {#at_least}, {#between}); matching
7
+ # letters of either case ({#case_insensitive}); captured under a name ({#captured}); and matching only where
8
+ # something else does or doesn't come before or after it ({#followed_by}, {#not_followed_by},
9
+ # {#preceded_by}, {#not_preceded_by}). It is a +Regexp+, so it goes wherever one does (+gsub+, +match?+,
10
+ # +case+, +validates format:+) as it is.
11
+ #
12
+ # Each variation is a new expression, frozen like the one it came from, so a pattern kept in a constant is
13
+ # never changed by a caller. Each end has at most one anchor: anchoring an end again replaces its anchor, so
14
+ # anchoring twice the same way is anchoring once.
15
+ #
16
+ # Repeating an expression repeats all of it: one that is more than a single unit is grouped first
17
+ # (+(?:ab)++), so +ab+ repeated is +abab+, never +abb+. An anchored expression cannot be repeated, since only
18
+ # one stretch of the text (or of a line) starts it; anchor after repeating.
19
+ #
20
+ # A body never holds an alternation at its top level: one is wrapped in +(?:…)+ and built with +single: true+,
21
+ # so a body can be followed, preceded or placed in a sequence as it is.
22
+ class Expression < Regexp
23
+ # What each kind of anchor writes at the start. A line starts at the start of the text, after a line feed,
24
+ # and after a carriage return that no line feed follows, so +\r\n+, +\r+ and +\n+ each end one line.
25
+ STARTS = {
26
+ text: '\A',
27
+ line: '(?:\A|(?<=\n)|(?<=\r)(?!\n))'
28
+ }.freeze
29
+ # What each kind of anchor writes at the end. A line ends at the end of the text, before a carriage return,
30
+ # and before a line feed that no carriage return comes before.
31
+ ENDS = {
32
+ text: '\z',
33
+ line: '(?:(?=\r|\z)|(?<!\r)(?=\n))'
34
+ }.freeze
35
+ # What a capture's name may be: what Ruby allows as one, and what +MatchData#[]+ reads by.
36
+ CAPTURE_NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/
37
+
38
+ # @param body [String] the expression's source, without anchors
39
+ # @param start [Symbol, nil] where it must match from: +:text+ (the text's start), +:line+ (a line's) or nil
40
+ # @param finish [Symbol, nil] where it must match to: +:text+ (the text's end), +:line+ (a line's) or nil
41
+ # @param single [Boolean] whether the body is one unit a quantifier applies to whole: a set, or a group
42
+ # @param options [Integer] +Regexp+ options, such as +Regexp::IGNORECASE+
43
+ def initialize(body, start: nil, finish: nil, single: false, options: 0)
44
+ @body = body
45
+ @start = start
46
+ @finish = finish
47
+ @single = single
48
+ super("#{STARTS.fetch(start) if start}#{body}#{ENDS.fetch(finish) if finish}", options)
49
+ freeze
50
+ end
51
+
52
+ # ── Anchors ─────────────────────────────────────────────────────────────────────────────────────────────
53
+
54
+ # +Regexes.lowercase_letters.one_or_more.leading+ matches the +ab+ of +ab1+, never the +cd+ of +1cd+. The
55
+ # start is the text's (+\A+), never a line's (+^+), so a later line cannot satisfy it.
56
+ #
57
+ # @return [Expression] the expression, matching only at the start of the text
58
+ def leading = varied(start: :text)
59
+
60
+ # +Regexes.lowercase_letters.one_or_more.trailing+ matches the +cd+ of +1cd+, never the +ab+ of +ab1+.
61
+ # The end is the text's (+\z+), never a line's (+$+), so a final newline is not passed over.
62
+ #
63
+ # @return [Expression] the expression, matching only at the end of the text
64
+ def trailing = varied(finish: :text)
65
+
66
+ # +Regexes.lowercase_letters.one_or_more.whole+ matches +abc+, never +abc1+.
67
+ #
68
+ # @return [Expression] the expression, matching only the whole of the text
69
+ def whole = varied(start: :text, finish: :text)
70
+
71
+ # +Regexes.lowercase_letters.one_or_more.line_leading+ finds +ab+ and +cd+ in +"ab1\r\ncd2"+: the start of
72
+ # each line, whether lines end in +\r\n+, +\r+ or +\n+. Unlike +^+, it never finds a line between the
73
+ # +\r+ and the +\n+ of one line break.
74
+ #
75
+ # @return [Expression] the expression, matching only at the start of a line
76
+ def line_leading = varied(start: :line)
77
+
78
+ # +Regexes.digits.one_or_more.line_trailing+ finds +1+ and +2+ in +"ab1\r\ncd2"+: the end of each line.
79
+ # Unlike +$+, it ends a line before a +\r\n+ or a lone +\r+, never only before a +\n+.
80
+ #
81
+ # @return [Expression] the expression, matching only at the end of a line
82
+ def line_trailing = varied(finish: :line)
83
+
84
+ # +Regexes.lowercase_letters.one_or_more.whole_line+ finds +cd+ in +"ab1\ncd"+, never +ab+.
85
+ #
86
+ # @return [Expression] the expression, matching only a whole line
87
+ def whole_line = varied(start: :line, finish: :line)
88
+
89
+ # @return [Boolean] whether it matches only at the start of the text
90
+ def leading? = @start == :text
91
+
92
+ # @return [Boolean] whether it matches only at the end of the text
93
+ def trailing? = @finish == :text
94
+
95
+ # @return [Boolean] whether it matches only at the start of a line
96
+ def line_leading? = @start == :line
97
+
98
+ # @return [Boolean] whether it matches only at the end of a line
99
+ def line_trailing? = @finish == :line
100
+
101
+ # ── Repetition ──────────────────────────────────────────────────────────────────────────────────────────
102
+
103
+ # +Regexes.lowercase_letters.one_or_more+ matches +abc+ in +abc1+ as one match, not three.
104
+ #
105
+ # @return [Expression] one or more of it in a row, as many as there are
106
+ def one_or_more = repeated('+')
107
+
108
+ # @return [Expression] none or more of it in a row, as many as there are
109
+ def zero_or_more = repeated('*')
110
+
111
+ # @return [Expression] it, or nothing
112
+ def optional = repeated('?')
113
+
114
+ # @param count [Integer] how many
115
+ # @return [Expression] exactly +count+ of it in a row
116
+ def exactly(count) = repeated("{#{Integer(count)}}")
117
+
118
+ # +Regexes.newline.at_least(3)+ matches three or more newlines in a row, never two.
119
+ #
120
+ # @param count [Integer] the fewest
121
+ # @return [Expression] +count+ or more of it in a row, as many as there are
122
+ def at_least(count) = repeated("{#{Integer(count)},}")
123
+
124
+ # +Regexes.any_character.between(1, 255)+ takes up to 255 characters at a time.
125
+ #
126
+ # @param min [Integer] the fewest
127
+ # @param max [Integer] the most
128
+ # @return [Expression] from +min+ to +max+ of it in a row, as many as there are
129
+ # @raise [ArgumentError] when +min+ is more than +max+
130
+ def between(min, max)
131
+ raise ArgumentError, "between(#{min}, #{max}): the fewest is more than the most" if Integer(min) > Integer(max)
132
+
133
+ repeated("{#{min},#{max}}")
134
+ end
135
+
136
+ # ── Case ────────────────────────────────────────────────────────────────────────────────────────────────
137
+
138
+ # +Regexes.http_scheme.case_insensitive+ matches +HTTPS://+ as well as +https://+.
139
+ #
140
+ # @return [Expression] the expression, matching letters of either case
141
+ def case_insensitive = varied(options: options | IGNORECASE)
142
+
143
+ # ── Captures ────────────────────────────────────────────────────────────────────────────────────────────
144
+
145
+ # +Regexes.digits.one_or_more.captured(:year)+ matches what it did, and +match[:year]+ reads it. Anchors
146
+ # stay outside the capture, so it holds only the text matched.
147
+ #
148
+ # @param name [Symbol, String] the capture's name: a letter or underscore, then letters, digits and
149
+ # underscores
150
+ # @return [Expression] the expression, its match captured under +name+
151
+ # @raise [ArgumentError] when +name+ can't name a capture
152
+ def captured(name)
153
+ raise ArgumentError, "#{name.inspect} can't name a capture: use letters, digits and _" unless
154
+ CAPTURE_NAME.match?(name.to_s)
155
+
156
+ Expression.new("(?<#{name}>#{@body})", start: @start, finish: @finish, single: true, options:)
157
+ end
158
+
159
+ # ── Lookarounds ─────────────────────────────────────────────────────────────────────────────────────────
160
+
161
+ # +Regexes.newline.followed_by(Regexes.space_or_tab)+ matches a line feed that a space or tab comes after,
162
+ # and takes only the line feed.
163
+ #
164
+ # @param other [Expression] what must come right after it
165
+ # @return [Expression] the expression, matching only where +other+ comes next, which it doesn't take
166
+ def followed_by(other) = looking("#{@body}(?=#{other.embedded})")
167
+
168
+ # +Regexes.literal('http').not_followed_by(Regexes.literal('s'))+ matches the +http+ of +http://+, never of
169
+ # +https://+.
170
+ #
171
+ # A repeated expression gives back what it took until the lookaround passes: +digits.one_or_more+ not followed
172
+ # by +%+ still matches the +5+ of +50%+. Exclude what it repeats too
173
+ # (+not_followed_by(Regexes.either(Regexes.digits, Regexes.literal('%')))+) to refuse the whole run.
174
+ #
175
+ # @param other [Expression] what must not come right after it
176
+ # @return [Expression] the expression, matching only where +other+ doesn't come next
177
+ def not_followed_by(other) = looking("#{@body}(?!#{other.embedded})")
178
+
179
+ # +Regexes.digits.one_or_more.preceded_by(Regexes.literal('$'))+ matches the +5+ of +$5+, and takes only
180
+ # the digits. Ruby allows only what has a known length, or alternatives each of one, before a match.
181
+ #
182
+ # @param other [Expression] what must come right before it
183
+ # @return [Expression] the expression, matching only where +other+ comes before, which it doesn't take
184
+ # @raise [RegexpError] when +other+ can match texts of different lengths in a way Ruby can't look behind
185
+ def preceded_by(other) = looking("(?<=#{other.embedded})#{@body}")
186
+
187
+ # +Regexes.lowercase_letters.one_or_more.not_preceded_by(Regexes.literal('@'))+ matches the +ada+ of
188
+ # +ada+, never the +acme+ of +@acme+.
189
+ #
190
+ # @param other [Expression] what must not come right before it
191
+ # @return [Expression] the expression, matching only where +other+ doesn't come before
192
+ # @raise [RegexpError] when +other+ can match texts of different lengths in a way Ruby can't look behind
193
+ def not_preceded_by(other) = looking("(?<!#{other.embedded})#{@body}")
194
+
195
+ # ── Composition ─────────────────────────────────────────────────────────────────────────────────────────
196
+
197
+ # The expression as a part of a larger one ({Regexes.sequence}, {Regexes.either}): its source as it is
198
+ # when it has no options, so the larger one reads as it would written out, or with its options carried
199
+ # along (+(?i-mx:…)+) when it has some, so a case-insensitive part stays so inside a case-sensitive whole.
200
+ #
201
+ # @return [String]
202
+ def embedded = options.zero? ? source : to_s
203
+
204
+ # ── ECMAScript ──────────────────────────────────────────────────────────────────────────────────────────
205
+
206
+ # The expression as ECMAScript writes it, for JavaScript (+new RegExp(source, flags)+, with {#ecma_flags})
207
+ # and for a JSON Schema +pattern+. Anchors become +^+ and +$+, which there anchor to the text:
208
+ #
209
+ # Regexes.uuid.whole.ecma_source # => "^(?<![0-9a-fA-F])[0-9a-fA-F]{8}-…(?![0-9a-fA-F])$"
210
+ #
211
+ # A JSON Schema +pattern+ searches, as an unanchored expression does, so give it a +.whole+ expression's.
212
+ #
213
+ # @return [String] the source, frozen
214
+ # @raise [UntranslatableError] when it uses what ECMAScript has no faithful equivalent for (+\X+, a name
215
+ # captured twice, atomic groups, inline options), rather than translate it into something else
216
+ def ecma_source = Ecma.source(self)
217
+
218
+ # @return [String] the flags {#ecma_source} needs: +u+ (Unicode, for its property escapes and strict
219
+ # escapes), and +i+ when the expression ignores case
220
+ # @raise [UntranslatableError] when it is in extended mode or lets +.+ match newlines
221
+ def ecma_flags = Ecma.flags(self)
222
+
223
+ protected
224
+
225
+ # @return [String] the body, as one unit a quantifier applies to whole
226
+ def unit = @single ? @body : "(?:#{@body})"
227
+
228
+ private
229
+
230
+ # @param changes [Hash{Symbol => Object}] what differs from this expression
231
+ # @return [Expression] this expression with the changes
232
+ def varied(**changes)
233
+ Expression.new(@body,
234
+ start: @start,
235
+ finish: @finish,
236
+ single: @single,
237
+ options:,
238
+ **changes)
239
+ end
240
+
241
+ # @param body [String] the body with a lookaround before or after it
242
+ # @return [Expression] an expression of that body, anchored as this one is
243
+ def looking(body) = Expression.new(body, start: @start, finish: @finish, options:)
244
+
245
+ # @param quantifier [String] the quantifier, as written after a unit
246
+ # @return [Expression] the expression repeated
247
+ # @raise [ArgumentError] when it is anchored
248
+ def repeated(quantifier)
249
+ raise ArgumentError, "#{inspect} is anchored: repeat it first, then anchor it" if @start || @finish
250
+
251
+ Expression.new("#{unit}#{quantifier}", options:)
252
+ end
253
+ end
254
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Characters and breaks ─────────────────────────────────────────────────────────────────────────────────
5
+
6
+ ANY_CHARACTER = Expression.new('.', single: true)
7
+ LINE_BREAK = Expression.new('(?:\r\n|\r|\n)', single: true)
8
+ UNICODE_LINE_BREAK = Expression.new('\R', single: true)
9
+ PARAGRAPH_BREAK = Expression.new("#{LINE_BREAK.source}(?:[ \\t]*#{LINE_BREAK.source})+")
10
+
11
+ # +Regexes.any_character.between(1, 255)+ takes text up to 255 characters at a time.
12
+ #
13
+ # @return [Expression] one character, any but a line feed
14
+ def any_character = ANY_CHARACTER
15
+
16
+ # +text.split(Regexes.line_break)+ splits lines however they end.
17
+ #
18
+ # @return [Expression] one line break, however it is written: +\r\n+, +\r+ or +\n+, the CRLF taken whole
19
+ def line_break = LINE_BREAK
20
+
21
+ # @return [Expression] one line break as Unicode defines them: {#line_break}'s three, the vertical tab, the
22
+ # form feed, the next line (+U+0085+) and the line and paragraph separators (+U+2028+, +U+2029+)
23
+ def unicode_line_break = UNICODE_LINE_BREAK
24
+
25
+ # +text.split(Regexes.paragraph_break)+ splits paragraphs, and +text.gsub(Regexes.paragraph_break, "\n\n")+
26
+ # closes up paragraphs left too far apart.
27
+ #
28
+ # @return [Expression] two or more line breaks, with nothing between them but spaces and tabs: the end of a
29
+ # paragraph and the blank lines after it
30
+ def paragraph_break = PARAGRAPH_BREAK
31
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Codes ─────────────────────────────────────────────────────────────────────────────────────────────────
5
+ #
6
+ # Codes that are only a set and a count are written with the set: an ISO 3166 alpha-2 country code is
7
+ # +Regexes.uppercase_letters.exactly(2)+, an ISO 4217 currency code +Regexes.uppercase_letters.exactly(3)+. The
8
+ # codes here have parts. None is checked against the list of codes assigned, nor a checksum.
9
+
10
+ alphanumeric_before = '(?<![A-Za-z0-9])'
11
+ alphanumeric_after = '(?![A-Za-z0-9])'
12
+ subtag_before = '(?<![A-Za-z0-9-])'
13
+ subtag_after = '(?![A-Za-z0-9-])'
14
+
15
+ E164_PHONE_NUMBER = Expression.new('(?<![0-9+])\+[1-9][0-9]{1,14}(?![0-9])')
16
+ IBAN = Expression.new(
17
+ "#{alphanumeric_before}(?<country_code>[A-Z]{2})(?<check_digits>[0-9]{2})(?<bban>[A-Z0-9]{11,30})" \
18
+ "#{alphanumeric_after}"
19
+ )
20
+ BIC = Expression.new(
21
+ "#{alphanumeric_before}(?<business_party_prefix>[A-Z0-9]{4})(?<country_code>[A-Z]{2})" \
22
+ "(?<business_party_suffix>[A-Z0-9]{2})(?<branch_identifier>[A-Z0-9]{3})?#{alphanumeric_after}"
23
+ )
24
+ LANGUAGE_TAG = Expression.new(
25
+ "#{subtag_before}(?<language>[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{5,8})" \
26
+ '(?:-(?<script>[A-Za-z]{4}))?' \
27
+ '(?:-(?<region>[A-Za-z]{2}|[0-9]{3}))?' \
28
+ '(?:-(?:[A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*' \
29
+ '(?:-[0-9A-WYZa-wyz](?:-[A-Za-z0-9]{2,8})+)*' \
30
+ "(?:-[Xx](?:-[A-Za-z0-9]{1,8})+)?#{subtag_after}"
31
+ )
32
+ HEX_COLOR = Expression.new('#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})(?![0-9a-fA-F])')
33
+
34
+ # +Regexes.e164_phone_number.whole+ matches <tt>+14155552671</tt> and <tt>+442071838750</tt>, never one without
35
+ # the plus, with spaces, with a +0+ after the plus, or of more than 15 digits (ITU-T E.164). It never matches
36
+ # inside a longer run of digits.
37
+ #
38
+ # @return [Expression] a phone number in E.164 form: a plus, then up to 15 digits, the first not 0
39
+ def e164_phone_number = E164_PHONE_NUMBER
40
+
41
+ # +Regexes.iban.whole+ matches +DE89370400440532013000+ and +GB82WEST12345698765432+, never one with spaces
42
+ # (its printed form), lowercase letters, or a length outside 15 to 34. The check digits are not verified.
43
+ # It captures +country_code+, +check_digits+ and +bban+ (ISO 13616).
44
+ #
45
+ # @return [Expression] an IBAN in its electronic form
46
+ def iban = IBAN
47
+
48
+ # +Regexes.bic.whole+ matches +DEUTDEFF+ and +DEUTDEFF500+, never +DEUTDEF+ or a lowercase one. It captures
49
+ # +business_party_prefix+, +country_code+, +business_party_suffix+ and +branch_identifier+ (ISO 9362).
50
+ #
51
+ # @return [Expression] a business identifier code, or SWIFT code: 8 or 11 characters
52
+ def bic = BIC
53
+
54
+ # +Regexes.language_tag.whole+ matches +en+, +en-US+, +zh-Hant-TW+, +es-419+ and +sr-Latn-RS+, never +e+,
55
+ # +en_US+ or +en-+. It captures +language+, +script+ and +region+ (BCP 47, RFC 5646 §2.1); variants,
56
+ # extensions and private use are matched but not captured. A language may be 2 to 3 letters or 5 to 8, so
57
+ # most short words have a tag's shape: validate a tag with +.whole+ rather than search prose for one.
58
+ #
59
+ # @return [Expression] a language tag, as HTTP's Accept-Language and HTML's +lang+ hold it
60
+ def language_tag = LANGUAGE_TAG
61
+
62
+ # +Regexes.hex_color.whole+ matches +#fff+, +#FFFFFF+, +#ffff+ and +#ff000080+, never +#ff+, +#fffff+ or +fff+.
63
+ #
64
+ # @return [Expression] a color in CSS hex notation: a hash and 3, 4, 6 or 8 hex digits
65
+ def hex_color = HEX_COLOR
66
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Identifiers ───────────────────────────────────────────────────────────────────────────────────────────
5
+
6
+ base64_digit = '[A-Za-z0-9+/]'
7
+ base64url_digit = '[A-Za-z0-9_-]'
8
+ before_two_pads = '[AQgw]'
9
+ before_one_pad = '[AEIMQUYcgkosw048]'
10
+ restricted = '[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}'
11
+ semver_part = '(?:0|[1-9][0-9]*)'
12
+ semver_label = '(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)'
13
+
14
+ IDENTIFIER = Expression.new('[A-Za-z][A-Za-z0-9_]*')
15
+ SNAKE_CASE = Expression.new('[a-z][a-z0-9]*(?:_[a-z0-9]+)*')
16
+ SCREAMING_SNAKE_CASE = Expression.new('[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*')
17
+ KEBAB_CASE = Expression.new('[a-z0-9]+(?:-[a-z0-9]+)*')
18
+ CAMEL_CASE = Expression.new('[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*')
19
+ PASCAL_CASE = Expression.new('(?:[A-Z][a-z0-9]*)+', single: true)
20
+ UUID = Expression.new(
21
+ '(?<![0-9a-fA-F])[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(?![0-9a-fA-F])'
22
+ )
23
+ ULID = Expression.new('(?<![0-9A-Za-z])[0-7][0-9A-HJKMNP-TV-Z]{25}(?![0-9A-Za-z])')
24
+ SEMANTIC_VERSION = Expression.new(
25
+ "(?<major>#{semver_part})\\.(?<minor>#{semver_part})\\.(?<patch>#{semver_part})" \
26
+ "(?:-(?<prerelease>#{semver_label}(?:\\.#{semver_label})*))?" \
27
+ '(?:\+(?<build>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?'
28
+ )
29
+ MEDIA_TYPE = Expression.new("(?<type>#{restricted})/(?<subtype>#{restricted})")
30
+ JSON_WEB_TOKEN = Expression.new(
31
+ "(?<header>eyJ#{base64url_digit}*)\\.(?<payload>eyJ#{base64url_digit}*)\\.(?<signature>#{base64url_digit}*)"
32
+ )
33
+ BASE64 = Expression.new(
34
+ "(?:#{base64_digit}{4})*" \
35
+ "(?:#{base64_digit}#{before_two_pads}==|#{base64_digit}{2}#{before_one_pad}=|#{base64_digit}{4})"
36
+ )
37
+ BASE64URL = Expression.new(
38
+ "(?:#{base64url_digit}{4})*" \
39
+ "(?:#{base64url_digit}#{before_two_pads}(?:==)?|#{base64url_digit}{2}#{before_one_pad}=?|#{base64url_digit}{4})"
40
+ )
41
+
42
+ # +Regexes.identifier.whole+ matches +get_order+ and +Tag2+, never +2tag+ or +get-order+.
43
+ #
44
+ # @return [Expression] a letter, then letters, digits and underscores
45
+ def identifier = IDENTIFIER
46
+
47
+ # +Regexes.snake_case.whole+ matches +order+, +line_item+ and +user_2fa+, never +lineItem+, +line__item+,
48
+ # +_line+ or +line_+.
49
+ #
50
+ # @return [Expression] lowercase words of letters and digits, the first starting with a letter, joined by
51
+ # single underscores
52
+ def snake_case = SNAKE_CASE
53
+
54
+ # +Regexes.screaming_snake_case.whole+ matches +MAX_RETRIES+ and +HTTP2+, never +Max_Retries+ or +MAX__RETRIES+.
55
+ #
56
+ # @return [Expression] uppercase words of letters and digits, the first starting with a letter, joined by single
57
+ # underscores: a constant's name, an environment variable's
58
+ def screaming_snake_case = SCREAMING_SNAKE_CASE
59
+
60
+ # +Regexes.kebab_case.whole+ matches +order-history+ and +2026-review+, never +Order-History+, +order--history+
61
+ # or +-order+. Unlike {#snake_case}, a word may start with a digit, as a URL's slug often does.
62
+ #
63
+ # @return [Expression] lowercase words of letters and digits joined by single hyphens
64
+ def kebab_case = KEBAB_CASE
65
+
66
+ # +Regexes.camel_case.whole+ matches +lineItem+, +getHTTPResponse+ and +order+, never +LineItem+ or
67
+ # +line_item+.
68
+ #
69
+ # @return [Expression] a lowercase letter, then letters and digits, each later word starting uppercase
70
+ def camel_case = CAMEL_CASE
71
+
72
+ # +Regexes.pascal_case.whole+ matches +LineItem+, +HTTPServer+ and +A+, never +lineItem+ or +Line_Item+.
73
+ #
74
+ # @return [Expression] words of letters and digits, each starting uppercase: a class's name
75
+ def pascal_case = PASCAL_CASE
76
+
77
+ # +Regexes.uuid+ matches +01890a5d-ac96-774b-bcce-b302099a8057+, with its hyphens, of any version and either
78
+ # case. It never matches inside a longer run of hex digits. Without its hyphens, a UUID is
79
+ # +Regexes.hex_digits.exactly(32)+.
80
+ #
81
+ # @return [Expression] a UUID in its hyphenated form (RFC 9562)
82
+ def uuid = UUID
83
+
84
+ # +Regexes.ulid.whole+ matches +01ARZ3NDEKTSV4RRFFQ69G5FAV+, never one with +I+, +L+, +O+ or +U+ in it, or a
85
+ # first character above +7+. Uppercase, as the spec writes it; add +.case_insensitive+ to read either.
86
+ #
87
+ # @return [Expression] a ULID: 26 digits of Crockford's base32
88
+ def ulid = ULID
89
+
90
+ # +Regexes.semantic_version.whole+ matches +1.0.0+, +2.1.3-rc.1+ and +1.0.0+build.5+, never +1.0+, +v1.0.0+
91
+ # or +01.0.0+. It captures +major+, +minor+, +patch+, +prerelease+ and +build+ (SemVer 2.0.0).
92
+ #
93
+ # @return [Expression] a semantic version
94
+ def semantic_version = SEMANTIC_VERSION
95
+
96
+ # +Regexes.media_type.whole+ matches +text/html+, +application/vnd.api+json+ and +image/svg+xml+, never
97
+ # +text+ or +text/html; charset=utf-8+ (its parameters are not matched). It captures +type+ and +subtype+
98
+ # (RFC 6838 §4.2).
99
+ #
100
+ # @return [Expression] a media type, or MIME type: a type, a slash and a subtype
101
+ def media_type = MEDIA_TYPE
102
+
103
+ # A JSON Web Token's three parts in base64url, joined by dots, the header and payload each the encoding of a
104
+ # JSON object (so starting +eyJ+), the signature empty when unsigned. Whether it decodes, and whether its
105
+ # signature holds, is for a JWT library. It captures +header+, +payload+ and +signature+ (RFC 7519).
106
+ #
107
+ # @return [Expression] a JSON Web Token in its compact form
108
+ def json_web_token = JSON_WEB_TOKEN
109
+
110
+ # +Regexes.base64.whole+ matches +QUJD+ and +QUI=+, never +QUJ+ (a length no padding fixes), +QU=I+, or +QR==+
111
+ # (its last digit carries bits the padding says aren't there). It is canonical base64, so what it matches
112
+ # Ruby's strict decoder (+unpack1('m0')+) decodes.
113
+ #
114
+ # @return [Expression] text in RFC 4648 base64, padded to a multiple of four, never empty
115
+ def base64 = BASE64
116
+
117
+ # +Regexes.base64url.whole+ matches +QUJD+, +QUI+ and +QUI=+, never +QU+J+, +Q+ or +QR+. Canonical, as {#base64}
118
+ # is.
119
+ #
120
+ # @return [Expression] text in RFC 4648 base64url, padded or not, never empty
121
+ def base64url = BASE64URL
122
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Mail ──────────────────────────────────────────────────────────────────────────────────────────────────
5
+
6
+ any_label = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?'
7
+ atext = "[A-Za-z0-9!\#$%&'*+/=?^_`{|}~-]"
8
+ dot_atom = "#{atext}+(?:\\.#{atext}+)*"
9
+
10
+ EMAIL_ADDRESS = Expression.new(
11
+ "(?<local>[A-Za-z0-9.!\#$%&'*+/=?^_`{|}~-]+)@(?<domain>#{any_label}(?:\\.#{any_label})*)"
12
+ )
13
+ MESSAGE_ID = Expression.new("<(?<id_left>#{dot_atom})@(?<id_right>#{dot_atom}|\\[[!-Z^-~]*\\])>")
14
+ HEADER_FIELD_NAME = Expression.new('[!-9;-~]+')
15
+ FOLDED_LINE_BREAK = Expression.new('\r\n(?=[ \t])')
16
+ UNFOLDED_LINE_BREAK = Expression.new('\r\n(?![ \t])')
17
+
18
+ # The address an HTML form's +type=email+ input accepts (WHATWG HTML §4.10.5.1.5), so a browser and a server
19
+ # reach the same verdict: +ada@acme.example+, +a+b@x+. Like the browser, it allows a domain of one label
20
+ # and dots anywhere in the local part. Whether the address exists is for the mail to find out. Its parts are
21
+ # captured as +local+ and +domain+.
22
+ #
23
+ # @return [Expression] an email address, as +ada@acme.example+
24
+ def email_address = EMAIL_ADDRESS
25
+
26
+ # +Regexes.message_id.whole+ matches +<01890a5d@acme.example>+ and +<a.b@[127.0.0.1]>+, never one without its
27
+ # angle brackets or its +@+. It captures +id_left+ and +id_right+ (RFC 5322 §3.6.4).
28
+ #
29
+ # @return [Expression] a mail message's identifier, as its Message-ID, In-Reply-To and References headers hold
30
+ # it
31
+ def message_id = MESSAGE_ID
32
+
33
+ # +Regexes.header_field_name.whole+ matches +Subject+, +X-Original-To+ and +DKIM-Signature+, never +Sub ject+
34
+ # or +Subject:+ (RFC 5322 §2.2: printable ASCII but the colon).
35
+ #
36
+ # @return [Expression] the name of a mail header field
37
+ def header_field_name = HEADER_FIELD_NAME
38
+
39
+ # A header that runs over several lines is folded: its line breaks are each followed by a space or tab, and
40
+ # unfolding it removes them (RFC 5322 §2.2.3).
41
+ #
42
+ # @return [Expression] a CRLF followed by a space or tab, which it does not take
43
+ def folded_line_break = FOLDED_LINE_BREAK
44
+
45
+ # @return [Expression] a CRLF not followed by a space or tab: one that ends a header, never one inside it
46
+ def unfolded_line_break = UNFOLDED_LINE_BREAK
47
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Network ───────────────────────────────────────────────────────────────────────────────────────────────
5
+
6
+ label = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'
7
+ any_label = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?'
8
+ octet = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])'
9
+ ipv4 = "#{octet}(?:\\.#{octet}){3}"
10
+ h16 = '[0-9a-fA-F]{1,4}'
11
+ ls32 = "(?:#{h16}:#{h16}|#{ipv4})"
12
+ ipv6 = [
13
+ "(?:#{h16}:){6}#{ls32}",
14
+ "::(?:#{h16}:){5}#{ls32}",
15
+ "(?:#{h16})?::(?:#{h16}:){4}#{ls32}",
16
+ "(?:(?:#{h16}:){0,1}#{h16})?::(?:#{h16}:){3}#{ls32}",
17
+ "(?:(?:#{h16}:){0,2}#{h16})?::(?:#{h16}:){2}#{ls32}",
18
+ "(?:(?:#{h16}:){0,3}#{h16})?::#{h16}:#{ls32}",
19
+ "(?:(?:#{h16}:){0,4}#{h16})?::#{ls32}",
20
+ "(?:(?:#{h16}:){0,5}#{h16})?::#{h16}",
21
+ "(?:(?:#{h16}:){0,6}#{h16})?::"
22
+ ].join('|').then { "(?:#{it})" }
23
+ pchar = "(?:[A-Za-z0-9\\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})"
24
+ hex_pair = '[0-9A-Fa-f]{2}'
25
+
26
+ URI_SCHEME = Expression.new('[A-Za-z][A-Za-z0-9+.-]*:')
27
+ HTTP_SCHEME = Expression.new('https?://')
28
+ HTTP_URL = Expression.new(
29
+ "https?://(?<host>#{any_label}(?:\\.#{any_label})*|\\[#{ipv6}\\])(?::(?<port>[0-9]{1,5}))?" \
30
+ "(?<path>(?:/#{pchar}*)*)(?:\\?(?<query>(?:#{pchar}|[/?])*))?(?:\\#(?<fragment>(?:#{pchar}|[/?])*))?"
31
+ )
32
+ DNS_LABEL = Expression.new(label, single: true)
33
+ DOMAIN_NAME = Expression.new("(?=[a-z0-9.-]{1,253}(?![a-z0-9.-]))#{label}(?:\\.#{label})+")
34
+ IPV4_ADDRESS = Expression.new("(?<![0-9])#{ipv4}(?![0-9])")
35
+ IPV6_ADDRESS = Expression.new("(?<![0-9a-fA-F:])#{ipv6}(?![0-9a-fA-F:])")
36
+ IP_ADDRESS = Expression.new("(?:#{IPV4_ADDRESS.source}|#{IPV6_ADDRESS.source})", single: true)
37
+ IPV4_CIDR = Expression.new("(?<address>#{IPV4_ADDRESS.source})/(?<prefix_length>3[0-2]|[12]?[0-9])(?![0-9])")
38
+ IPV6_CIDR = Expression.new(
39
+ "(?<address>#{IPV6_ADDRESS.source})/(?<prefix_length>12[0-8]|1[01][0-9]|[1-9]?[0-9])(?![0-9])"
40
+ )
41
+ MAC_ADDRESS = Expression.new(
42
+ "(?<![0-9A-Fa-f:-])(?:#{hex_pair}(?::#{hex_pair}){5}|#{hex_pair}(?:-#{hex_pair}){5})(?![0-9A-Fa-f:-])"
43
+ )
44
+
45
+ # +Regexes.uri_scheme.leading+ finds the +mailto:+ of +mailto:ada@acme.example+ and the +https:+ of a web link.
46
+ # Either case, as RFC 3986 §3.1 allows, so +.leading+ is its usual use.
47
+ #
48
+ # @return [Expression] a URI's scheme and the colon that ends it
49
+ def uri_scheme = URI_SCHEME
50
+
51
+ # +Regexes.http_scheme.leading.case_insensitive+ tells a web link from a +cid:+ or +mailto:+ one.
52
+ #
53
+ # @return [Expression] +http://+ or +https://+, in lowercase
54
+ def http_scheme = HTTP_SCHEME
55
+
56
+ # +Regexes.http_url.whole+ matches +https://acme.example+, +http://[::1]:8080/a?b=c#d+ and
57
+ # +https://en.wikipedia.org/wiki/Ruby_(programming_language)+, never +https://+, +ftp://acme.example+, one
58
+ # with a space or with user and password before the host. Every character after the host is one RFC 3986
59
+ # allows there, and a +%+ starts a valid escape. It captures +host+, +port+, +path+, +query+ and +fragment+.
60
+ #
61
+ # In prose, a sentence's full stop after a link is a character a path allows, so it is matched; trim
62
+ # +Regexes.literal('.').trailing+ from what it finds there.
63
+ #
64
+ # @return [Expression] an http or https URL with a host
65
+ def http_url = HTTP_URL
66
+
67
+ # +Regexes.dns_label.whole+ matches +acme+ and +mail-1+, never +-acme+, +acme-+, +Acme+ or a label of more
68
+ # than 63 characters (RFC 1035 §2.3.4). An internationalized label is matched in its ASCII form, +xn--…+.
69
+ #
70
+ # @return [Expression] one label of a domain name, lowercase: letters, digits and inner hyphens
71
+ def dns_label = DNS_LABEL
72
+
73
+ # +Regexes.domain_name.whole+ matches +acme.example+ and +mail.acme.co.uk+, never +acme+, +acme..example+,
74
+ # +acme.example.+ (a trailing dot) or a name of more than 253 characters.
75
+ #
76
+ # @return [Expression] two or more lowercase {#dns_label}s joined by dots
77
+ def domain_name = DOMAIN_NAME
78
+
79
+ # +Regexes.ipv4_address.whole+ matches +192.168.0.1+ and +0.0.0.0+, never +256.1.1.1+, +1.2.3+ or +01.2.3.4+
80
+ # (a leading zero, which some parsers read as octal). It never matches inside a longer run of digits.
81
+ #
82
+ # @return [Expression] an IPv4 address in dotted-decimal form
83
+ def ipv4_address = IPV4_ADDRESS
84
+
85
+ # +Regexes.ipv6_address.whole+ matches +2001:db8::1+, +::1+, +::+ and +::ffff:192.0.2.1+, never +1:::2+,
86
+ # +1::2::3+ or one with a zone (+fe80::1%eth0+). Every form RFC 4291 §2.2 writes, in either case.
87
+ #
88
+ # @return [Expression] an IPv6 address
89
+ def ipv6_address = IPV6_ADDRESS
90
+
91
+ # @return [Expression] an {#ipv4_address} or an {#ipv6_address}
92
+ def ip_address = IP_ADDRESS
93
+
94
+ # +Regexes.ipv4_cidr.whole+ matches +10.0.0.0/8+ and +192.168.1.0/24+, never +10.0.0.0/33+. Whether host bits
95
+ # are set is not checked. It captures +address+ and +prefix_length+.
96
+ #
97
+ # @return [Expression] an IPv4 network in CIDR notation: an address, a slash and a prefix length of 0 to 32
98
+ def ipv4_cidr = IPV4_CIDR
99
+
100
+ # +Regexes.ipv6_cidr.whole+ matches +2001:db8::/32+ and +::/0+, never +::/129+. It captures +address+ and
101
+ # +prefix_length+.
102
+ #
103
+ # @return [Expression] an IPv6 network in CIDR notation: an address, a slash and a prefix length of 0 to 128
104
+ def ipv6_cidr = IPV6_CIDR
105
+
106
+ # +Regexes.mac_address.whole+ matches +00:1A:2B:3C:4D:5E+ and +00-1a-2b-3c-4d-5e+, never one mixing colons and
107
+ # hyphens, or of five pairs.
108
+ #
109
+ # @return [Expression] a MAC address (EUI-48): six pairs of hex digits joined by colons or by hyphens
110
+ def mac_address = MAC_ADDRESS
111
+ end