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,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Numbers ───────────────────────────────────────────────────────────────────────────────────────────────
5
+
6
+ INTEGER = Expression.new('-?[0-9]+')
7
+ UNSIGNED_INTEGER = Expression.new('[0-9]+')
8
+ POSITIVE_INTEGER = Expression.new('[1-9][0-9]*')
9
+ DECIMAL = Expression.new('-?[0-9]+(?:\.[0-9]+)?')
10
+ UNSIGNED_DECIMAL = Expression.new('[0-9]+(?:\.[0-9]+)?')
11
+ JSON_NUMBER = Expression.new('-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?')
12
+ LATITUDE = Expression.new('-?(?:90(?:\.0+)?|[1-8]?[0-9](?:\.[0-9]+)?)')
13
+ LONGITUDE = Expression.new('-?(?:180(?:\.0+)?|(?:1[0-7][0-9]|[1-9]?[0-9])(?:\.[0-9]+)?)')
14
+ PORT_NUMBER = Expression.new(
15
+ '(?<![0-9])(?:6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}|0)(?![0-9])'
16
+ )
17
+
18
+ # +Regexes.integer.whole+ matches +42+, +-7+ and +007+, never +4.2+, +1e3+ or +1,000+. Leading zeros are
19
+ # allowed; {#positive_integer} refuses them.
20
+ #
21
+ # @return [Expression] a whole number, negative or not, in ASCII digits
22
+ def integer = INTEGER
23
+
24
+ # +Regexes.unsigned_integer.whole+ matches +0+, +42+ and +007+, never +-7+.
25
+ #
26
+ # @return [Expression] a whole number without a sign
27
+ def unsigned_integer = UNSIGNED_INTEGER
28
+
29
+ # +Regexes.positive_integer.whole+ matches +1+ and +42+, never +0+, +007+ or +-7+: a page number, a count.
30
+ #
31
+ # @return [Expression] a whole number of at least 1, written without leading zeros
32
+ def positive_integer = POSITIVE_INTEGER
33
+
34
+ # +Regexes.decimal.whole+ matches +42+, +-7.5+ and +0.25+, never +.5+, +5.+ or +1e3+. With +places:+, the
35
+ # number of digits after the point is fixed: +decimal(places: 2)+ is money written to the cent (+12.50+),
36
+ # +decimal(places: 0..6)+ a token amount of up to six places, the point left out when there are none.
37
+ #
38
+ # @param places [Integer, Range<Integer>, nil] how many digits must follow the point, or nil for any number
39
+ # @return [Expression] a number in ASCII digits, negative or not, with an optional fraction after a point
40
+ # @raise [ArgumentError] when +places+ is negative or not an Integer or Range of them
41
+ def decimal(places: nil) = places.nil? ? DECIMAL : with_places('-?[0-9]+', places)
42
+
43
+ # +Regexes.unsigned_decimal.whole+ matches +42+ and +0.25+, never +-7.5+. +places:+ is as for {#decimal}.
44
+ #
45
+ # @param places [Integer, Range<Integer>, nil] how many digits must follow the point, or nil for any number
46
+ # @return [Expression] a number in ASCII digits, without a sign, with an optional fraction after a point
47
+ # @raise [ArgumentError] when +places+ is negative or not an Integer or Range of them
48
+ def unsigned_decimal(places: nil) = places.nil? ? UNSIGNED_DECIMAL : with_places('[0-9]+', places)
49
+
50
+ # +Regexes.json_number.whole+ matches +0+, +-12.5+ and +6.02e23+, never +01+, +.5+, +1.+ or +NaN+ (RFC 8259
51
+ # §6).
52
+ #
53
+ # @return [Expression] a number as JSON writes it
54
+ def json_number = JSON_NUMBER
55
+
56
+ # +Regexes.latitude.whole+ matches +51.5074+, +-90+ and +0+, never +90.1+ or +91+.
57
+ #
58
+ # @return [Expression] a latitude in decimal degrees, from -90 to 90
59
+ def latitude = LATITUDE
60
+
61
+ # +Regexes.longitude.whole+ matches +-0.1278+, +180+ and +-179.99+, never +180.5+ or +181+.
62
+ #
63
+ # @return [Expression] a longitude in decimal degrees, from -180 to 180
64
+ def longitude = LONGITUDE
65
+
66
+ # +Regexes.port_number.whole+ matches +0+, +443+ and +65535+, never +65536+ or +0443+. It never matches inside a
67
+ # longer run of digits.
68
+ #
69
+ # @return [Expression] a TCP or UDP port number, 0 to 65535, without leading zeros
70
+ def port_number = PORT_NUMBER
71
+
72
+ private
73
+
74
+ # @param whole [String] the source of the part before the point
75
+ # @param places [Integer, Range<Integer>] how many digits must follow the point
76
+ # @return [Expression] a number with that many digits after the point, the point left out when none may
77
+ # follow
78
+ # @raise [ArgumentError] when +places+ is negative or not an Integer or Range of them
79
+ def with_places(whole, places)
80
+ min, max = places.is_a?(Range) ? [places.begin, places.end] : [places, places]
81
+ raise ArgumentError, "places: #{places.inspect} is not a count of digits" unless counts?(min, max)
82
+
83
+ fewest = [min, 1].max
84
+ count = fewest == max ? max.to_s : "#{fewest},#{max}"
85
+ fraction = max.zero? ? '' : "(?:\\.[0-9]{#{count}})#{'?' if min.zero?}"
86
+ Expression.new("#{whole}#{fraction}")
87
+ end
88
+
89
+ # @param min [Object] the fewest digits asked for
90
+ # @param max [Object] the most digits asked for
91
+ # @return [Boolean] whether they are counts of digits: whole numbers, not negative, the fewest not above the most
92
+ def counts?(min, max) = [min, max].all? { it.is_a?(Integer) && !it.negative? } && min <= max
93
+ end
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Sets of characters ────────────────────────────────────────────────────────────────────────────────────
5
+ #
6
+ # Each matches one character of its set, and is named for the set (plural). ASCII unless the name says
7
+ # otherwise.
8
+
9
+ LOWERCASE_LETTERS = CharacterClass.new('a-z')
10
+ UPPERCASE_LETTERS = CharacterClass.new('A-Z')
11
+ LETTERS = CharacterClass.new('A-Za-z')
12
+ DIGITS = CharacterClass.new('0-9')
13
+ LOWERCASE_ALPHANUMERIC = CharacterClass.new('a-z0-9')
14
+ UPPERCASE_ALPHANUMERIC = CharacterClass.new('A-Z0-9')
15
+ ALPHANUMERIC = CharacterClass.new('A-Za-z0-9')
16
+ WORD_CHARACTERS = CharacterClass.new('A-Za-z0-9_')
17
+ BINARY_DIGITS = CharacterClass.new('01')
18
+ OCTAL_DIGITS = CharacterClass.new('0-7')
19
+ HEX_DIGITS = CharacterClass.new('0-9a-fA-F')
20
+ BASE32_DIGITS = CharacterClass.new('A-Z2-7')
21
+ BASE58_DIGITS = CharacterClass.new('1-9A-HJ-NP-Za-km-z')
22
+ BASE64_DIGITS = CharacterClass.new('A-Za-z0-9+/')
23
+ BASE64URL_DIGITS = CharacterClass.new('A-Za-z0-9\-_')
24
+ WHITESPACE = CharacterClass.new('[:space:]')
25
+ ASCII_WHITESPACE = CharacterClass.new(' \t\n\v\f\r')
26
+ SPACE_OR_TAB = CharacterClass.new(' \t')
27
+ NEWLINE = CharacterClass.new('\n')
28
+ SLASH = CharacterClass.new('/')
29
+ HYPHEN = CharacterClass.new('\-')
30
+ DASHES = CharacterClass.new('\p{Pd}')
31
+ APOSTROPHES = CharacterClass.new("'`\u00B4\u02BC\u2018\u2019")
32
+ DOUBLE_QUOTES = CharacterClass.new("\"\u201C\u201D\u201E\u201F")
33
+ UNICODE_LETTERS = CharacterClass.new('\p{L}')
34
+ UNICODE_DIGITS = CharacterClass.new('\p{Nd}')
35
+ COMBINING_MARKS = CharacterClass.new('\p{M}')
36
+ CONTROL_CHARACTERS = CharacterClass.new('\p{Cc}')
37
+ FORMAT_CHARACTERS = CharacterClass.new('\p{Cf}')
38
+
39
+ # +Regexes.lowercase_letters+ matches the +a+ of +A1a+.
40
+ #
41
+ # @return [CharacterClass] one lowercase ASCII letter, +a+ to +z+
42
+ def lowercase_letters = LOWERCASE_LETTERS
43
+
44
+ # +Regexes.uppercase_letters+ matches the +A+ of +A1a+. +Regexes.uppercase_letters.exactly(2)+ is the shape of
45
+ # an ISO 3166 alpha-2 country code, and +.exactly(3)+ of an ISO 4217 currency code.
46
+ #
47
+ # @return [CharacterClass] one uppercase ASCII letter, +A+ to +Z+
48
+ def uppercase_letters = UPPERCASE_LETTERS
49
+
50
+ # @return [CharacterClass] one ASCII letter of either case
51
+ def letters = LETTERS
52
+
53
+ # +Regexes.digits.between(12, 19)+ is the shape of a payment card number, its digits run together.
54
+ #
55
+ # @return [CharacterClass] one ASCII digit, +0+ to +9+ (never another script's: that is {#unicode_digits})
56
+ def digits = DIGITS
57
+
58
+ # +Regexes.lowercase_alphanumeric+ matches the +a+ and the +1+ of +A1a+.
59
+ #
60
+ # @return [CharacterClass] one lowercase ASCII letter or ASCII digit
61
+ def lowercase_alphanumeric = LOWERCASE_ALPHANUMERIC
62
+
63
+ # +Regexes.uppercase_alphanumeric.between(1, 16)+ is a short code such as a voucher's.
64
+ #
65
+ # @return [CharacterClass] one uppercase ASCII letter or ASCII digit
66
+ def uppercase_alphanumeric = UPPERCASE_ALPHANUMERIC
67
+
68
+ # @return [CharacterClass] one ASCII letter of either case or ASCII digit
69
+ def alphanumeric = ALPHANUMERIC
70
+
71
+ # @return [CharacterClass] one ASCII letter, ASCII digit or underscore: what +\w+ matches in Ruby
72
+ def word_characters = WORD_CHARACTERS
73
+
74
+ # @return [CharacterClass] one binary digit, +0+ or +1+
75
+ def binary_digits = BINARY_DIGITS
76
+
77
+ # @return [CharacterClass] one octal digit, +0+ to +7+
78
+ def octal_digits = OCTAL_DIGITS
79
+
80
+ # +Regexes.hex_digits.exactly(64)+ is a SHA-256 digest written in hex, and +.exactly(32)+ a UUID written
81
+ # without its hyphens.
82
+ #
83
+ # @return [CharacterClass] one hexadecimal digit, +0+ to +9+ and +a+ to +f+ of either case
84
+ def hex_digits = HEX_DIGITS
85
+
86
+ # @return [CharacterClass] one digit of RFC 4648 base32: +A+ to +Z+ and +2+ to +7+, in uppercase
87
+ def base32_digits = BASE32_DIGITS
88
+
89
+ # Base58 leaves out the characters easy to misread: +0+, +O+, +I+ and +l+.
90
+ #
91
+ # @return [CharacterClass] one digit of the base58 alphabet Bitcoin defined, which others since share
92
+ def base58_digits = BASE58_DIGITS
93
+
94
+ # @return [CharacterClass] one digit of RFC 4648 base64: letters, digits, +++ and +/+ (never the +=+ padding)
95
+ def base64_digits = BASE64_DIGITS
96
+
97
+ # @return [CharacterClass] one digit of RFC 4648 base64url: letters, digits, +-+ and +_+, safe in a URL
98
+ def base64url_digits = BASE64URL_DIGITS
99
+
100
+ # Text copied from a web page holds no-break and wide spaces; this matches them, where {#ascii_whitespace}
101
+ # does not.
102
+ #
103
+ # @return [CharacterClass] one whitespace character of any script: spaces, tabs, line breaks, and the
104
+ # no-break and wide spaces
105
+ def whitespace = WHITESPACE
106
+
107
+ # @return [CharacterClass] one ASCII whitespace character: space, tab, line feed, vertical tab, form feed or
108
+ # carriage return, what +\s+ matches in Ruby
109
+ def ascii_whitespace = ASCII_WHITESPACE
110
+
111
+ # @return [CharacterClass] one space or tab: what RFC 5322 calls WSP, which folds a mail header
112
+ def space_or_tab = SPACE_OR_TAB
113
+
114
+ # +Regexes.newline.at_least(3)+ matches the blank lines between paragraphs left too far apart.
115
+ #
116
+ # @return [CharacterClass] one line feed, +\n+
117
+ def newline = NEWLINE
118
+
119
+ # +Regexes.slash.excluded.one_or_more+ matches one segment of a path.
120
+ #
121
+ # @return [CharacterClass] one forward slash
122
+ def slash = SLASH
123
+
124
+ # @return [CharacterClass] one hyphen-minus, +-+
125
+ def hyphen = HYPHEN
126
+
127
+ # +text.gsub(Regexes.dashes, '-')+ turns the en and em dashes a word processor types into hyphens.
128
+ #
129
+ # @return [CharacterClass] one dash of any kind Unicode names one (its Pd category): the hyphen-minus, the
130
+ # hyphen, the en and em dashes, and the rest
131
+ def dashes = DASHES
132
+
133
+ # +name.gsub(Regexes.apostrophes, "'")+ makes +O’Brien+ and +O`Brien+ one name.
134
+ #
135
+ # @return [CharacterClass] one character typed for an apostrophe: +'+, the curly quotes +‘+ and +’+, the
136
+ # modifier letter +ʼ+, the backtick and the acute accent
137
+ def apostrophes = APOSTROPHES
138
+
139
+ # @return [CharacterClass] one double quotation mark: +"+ and the curly +“+, +”+, +„+ and +‟+
140
+ def double_quotes = DOUBLE_QUOTES
141
+
142
+ # @return [CharacterClass] one letter of any script (Unicode's L category), as +é+, +ß+, +ж+ and +中+
143
+ def unicode_letters = UNICODE_LETTERS
144
+
145
+ # @return [CharacterClass] one decimal digit of any script (Unicode's Nd category), as +٣+ and +३+ as well as
146
+ # +3+
147
+ def unicode_digits = UNICODE_DIGITS
148
+
149
+ # +text.unicode_normalize(:nfd).gsub(Regexes.combining_marks, '')+ takes the accents off +café+.
150
+ #
151
+ # @return [CharacterClass] one combining mark (Unicode's M category): an accent or other mark that joins the
152
+ # character before it
153
+ def combining_marks = COMBINING_MARKS
154
+
155
+ # @return [CharacterClass] one control character (Unicode's Cc category): C0 (+\x00+ to +\x1F+), DEL and C1,
156
+ # which includes the tab and line breaks
157
+ def control_characters = CONTROL_CHARACTERS
158
+
159
+ # +text.gsub(Regexes.format_characters, '')+ takes out the invisible characters pasted text carries.
160
+ #
161
+ # @return [CharacterClass] one invisible formatting character (Unicode's Cf category): the zero-width joiner
162
+ # and non-joiner, the byte order mark, the soft hyphen and the direction marks
163
+ def format_characters = FORMAT_CHARACTERS
164
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Text ──────────────────────────────────────────────────────────────────────────────────────────────────
5
+
6
+ # A pattern written two ways (a name in braces or bare) captures the name once, in a lookahead before the two,
7
+ # so no capture's name is used twice and ECMAScript can read it.
8
+ name = '[A-Za-z_][A-Za-z0-9_]*'
9
+ destination = '[^()\s]+(?:\([^()\s]*\)[^()\s]*)*'
10
+ tag_name = '[^{}\s](?:[^{}]*[^{}\s])?'
11
+ sigil = '[#^/!&>]'
12
+ blank = '[ \t]*'
13
+ line_break = '(?:\r\n|\r|\n)'
14
+ # One character of a code span: anything but a line break, or a line break that doesn't end a paragraph.
15
+ span_char = "(?:[^\\r\\n]|#{line_break}(?![ \\t]*(?:\\r|\\n|\\z)))"
16
+
17
+ MARKDOWN_CODE_SPAN = Expression.new(
18
+ "(?<!`)(?<fence>`+)(?!`)(?<code>(?:(?!(?<!`)\\k<fence>(?!`))#{span_char})+)(?<!`)\\k<fence>(?!`)"
19
+ )
20
+ MARKDOWN_CODE_BLOCK = Expression.new(
21
+ "(?<fence>(?<marker>[`~])\\k<marker>{2,})[ \\t]*(?<language>[^\\s`]+)?[^`\\r\\n]*#{line_break}" \
22
+ "(?<code>(?:[^\\r\\n]*#{line_break})*?) {0,3}\\k<fence>\\k<marker>*[ \\t]*(?=\\r|\\n|\\z)"
23
+ )
24
+ MARKDOWN_LINK = Expression.new("\\[(?<text>[^\\[\\]\\n]+)\\]\\((?<destination>#{destination})\\)")
25
+ RUBY_FORMAT_REFERENCE = Expression.new(
26
+ "(?<!%)%(?=[{<](?<name>#{name}))(?:\\{#{name}\\}|<#{name}>[-+ 0#]*[0-9]*(?:\\.[0-9]+)?[A-Za-z])"
27
+ )
28
+ MUSTACHE_TAG = Expression.new(
29
+ "\\{\\{(?=(?:\\{|#{blank}(?<sigil>#{sigil})?)#{blank}(?<name>#{tag_name}))" \
30
+ "(?:\\{#{blank}#{tag_name}#{blank}\\}|#{blank}#{sigil}?#{blank}#{tag_name}#{blank})\\}\\}"
31
+ )
32
+ SHELL_VARIABLE_REFERENCE = Expression.new("(?<!\\\\)\\$(?=\\{?(?<name>#{name}))(?:\\{#{name}\\}|#{name})")
33
+ FILE_EXTENSION = Expression.new('\.(?<extension>[A-Za-z0-9]+)')
34
+ EMOJI = Expression.new(
35
+ '(?=\p{Extended_Pictographic}|\p{Regional_Indicator}|[0-9#*]️?⃣)\X'
36
+ )
37
+
38
+ # Markdown's inline code, a code span in CommonMark's terms (§6.1): +`get_order`+, and +``a ` b``+, whose fence of
39
+ # two backticks lets it hold one. It closes at the first run of exactly as many backticks as opened it, and may
40
+ # run over a line break but never a blank line, which ends the paragraph. It captures +code+, as written: the
41
+ # one space CommonMark strips from each end when both are there is kept; and +fence+, the backticks.
42
+ #
43
+ # @return [Expression] text between two runs of the same number of backticks, never empty
44
+ def markdown_code_span = MARKDOWN_CODE_SPAN
45
+
46
+ # +Regexes.markdown_code_block.line_leading+ matches a fenced code block (CommonMark §4.5): a line of three or
47
+ # more backticks or tildes and an optional info string, the code's lines, and a line closing it with at least as
48
+ # many of the same character. It captures +language+, the first word of the info string (+ruby+ of
49
+ # <tt>```ruby</tt>), nil when there is none; +code+, the lines between the fences, each with its line break; and
50
+ # +fence+ and +marker+, which close it. A block never closed (which CommonMark lets run to the end of the
51
+ # document) and an opening fence indented are not matched; +.line_leading+ requires the fence to start a line.
52
+ #
53
+ # @return [Expression] a fenced code block, from its opening fence to its closing one
54
+ def markdown_code_block = MARKDOWN_CODE_BLOCK
55
+
56
+ # +Regexes.markdown_link+ matches +[the docs](https://acme.example/docs)+ and
57
+ # +[Ruby](https://en.wikipedia.org/wiki/Ruby_(programming_language))+ (one level of parentheses), never a link
58
+ # with a title (+[a](b "t")+), an image's +![+ before it, or a reference link (+[a][1]+) — though an image's
59
+ # link part is matched from its +[+. It captures +text+ and +destination+ (CommonMark §6.3).
60
+ #
61
+ # @return [Expression] an inline Markdown link: text in brackets, then its destination in parentheses
62
+ def markdown_link = MARKDOWN_LINK
63
+
64
+ # +Regexes.ruby_format_reference+ finds +%{name}+ and +%<count>d+ in a string for +Kernel#format+ or I18n,
65
+ # never the escaped +%%{name}+. It captures +name+.
66
+ #
67
+ # @return [Expression] a named reference in a Ruby format string: +%{name}+, or +%<name>+ and its format
68
+ def ruby_format_reference = RUBY_FORMAT_REFERENCE
69
+
70
+ # +Regexes.mustache_tag+ finds +{{name}}+, +{{{html}}}+, +{{#items}}+ and +{{/items}}+ in a template, as
71
+ # Mustache, Handlebars and i18next write them. It captures +name+, and +sigil+ for a section, inverted
72
+ # section, end, comment, unescaped or partial tag.
73
+ #
74
+ # @return [Expression] a tag in a Mustache template
75
+ def mustache_tag = MUSTACHE_TAG
76
+
77
+ # +Regexes.shell_variable_reference+ finds +$HOME+ and +${PORT}+, never the escaped +\$HOME+ or the expansions
78
+ # +${PORT:-3000}+ and +$1+. It captures +name+.
79
+ #
80
+ # @return [Expression] a reference to a variable as a POSIX shell, Docker Compose or a +.env+ file writes it
81
+ def shell_variable_reference = SHELL_VARIABLE_REFERENCE
82
+
83
+ # +Regexes.file_extension.trailing+ finds the +.gz+ of +backup.tar.gz+ and nothing in +README+. It captures
84
+ # +extension+, without the dot.
85
+ #
86
+ # @return [Expression] a dot and the letters and digits after it: a file name's extension
87
+ def file_extension = FILE_EXTENSION
88
+
89
+ # +Regexes.emoji+ finds +👍🏽+, +👨‍👩‍👧+ and +🇩🇪+ each whole, with their skin tones, joiners and paired flags, and
90
+ # the keycap +1️⃣+. A character Unicode marks pictographic counts, so +©+ and +™+ do; a plain digit does not.
91
+ #
92
+ # @return [Expression] one emoji, as the one character a reader sees
93
+ def emoji = EMOJI
94
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # ── Times ─────────────────────────────────────────────────────────────────────────────────────────────────
5
+ #
6
+ # Each field is checked against its range (month 01–12, day 01–31, hour 00–23, minute 00–59, second 00–60,
7
+ # for a leap second), never against the calendar. A pattern that starts or ends with a digit never matches
8
+ # inside a longer run of digits.
9
+
10
+ year = '[0-9]{4}'
11
+ month = '(?:0[1-9]|1[0-2])'
12
+ day = '(?:0[1-9]|[12][0-9]|3[01])'
13
+ hour = '(?:[01][0-9]|2[0-3])'
14
+ minute = '[0-5][0-9]'
15
+ second = '(?:[0-5][0-9]|60)'
16
+ fraction = '(?:\.[0-9]+)'
17
+ offset = "(?:Z|[+-]#{hour}:?#{minute})"
18
+ date = "#{year}-#{month}-#{day}"
19
+ time = "#{hour}:#{minute}(?::#{second}#{fraction}?)?"
20
+ quantity = '[0-9]+'
21
+ before = '(?<![0-9])'
22
+ after = '(?![0-9])'
23
+
24
+ UTC_OFFSET = Expression.new(offset, single: true)
25
+ ISO8601_DATE = Expression.new("#{before}#{date}#{after}")
26
+ ISO8601_YEAR_MONTH = Expression.new("#{before}#{year}-#{month}#{after}")
27
+ ISO8601_TIME = Expression.new("#{before}#{time}#{after}")
28
+ ISO8601_DATE_TIME = Expression.new("#{before}#{date}[T ]#{time}(?:#{offset}|#{after})")
29
+ ISO8601_DURATION = Expression.new(
30
+ "P(?=[0-9]|T[0-9])(?:#{quantity}Y)?(?:#{quantity}M)?(?:#{quantity}W)?(?:#{quantity}D)?" \
31
+ "(?:T(?=[0-9])(?:#{quantity}H)?(?:#{quantity}M)?(?:#{quantity}#{fraction}?S)?)?"
32
+ )
33
+ RFC3339_TIMESTAMP = Expression.new(
34
+ "#{before}#{date}[Tt ]#{hour}:#{minute}:#{second}#{fraction}?(?:[Zz]|[+-]#{hour}:#{minute})"
35
+ )
36
+
37
+ # +Regexes.utc_offset+ matches +Z+, +-05:00+ and +-0500+: hours to 23, minutes to 59.
38
+ #
39
+ # @return [Expression] how far a time is from UTC, as ISO 8601 writes it
40
+ def utc_offset = UTC_OFFSET
41
+
42
+ # +Regexes.iso8601_date.whole+ matches +2026-11-21+, never +2026-13-01+, +2026-11-32+ or +20261121+.
43
+ # +2026-02-30+ is a date's shape.
44
+ #
45
+ # @return [Expression] a calendar date as ISO 8601's extended format writes it
46
+ def iso8601_date = ISO8601_DATE
47
+
48
+ # +Regexes.iso8601_year_month.whole+ matches +2026-11+, never +2026-13+ or +202611+: a billing period, a
49
+ # report's month.
50
+ #
51
+ # @return [Expression] a year and month as ISO 8601's extended format writes them
52
+ def iso8601_year_month = ISO8601_YEAR_MONTH
53
+
54
+ # +Regexes.iso8601_time.whole+ matches +14:30+, +14:30:05+ and +23:59:60.5+ (a leap second), never +24:00+,
55
+ # +14:60+ or +1430+. It is the time of day alone, without an offset: a date and time is {#iso8601_date_time}.
56
+ #
57
+ # @return [Expression] a time of day as ISO 8601's extended format writes it, seconds and fraction optional
58
+ def iso8601_time = ISO8601_TIME
59
+
60
+ # +Regexes.iso8601_date_time.whole+ matches +2026-11-21T14:30+, +2026-11-21 14:30:05.123Z+ and
61
+ # +2026-11-21T14:30:05-05:00+, never a date alone. A space may stand for the +T+, as RFC 3339 allows.
62
+ #
63
+ # @return [Expression] an {#iso8601_date} and an {#iso8601_time}, then an optional {#utc_offset}
64
+ def iso8601_date_time = ISO8601_DATE_TIME
65
+
66
+ # +Regexes.iso8601_duration.whole+ matches +P1Y2M10D+, +PT1H30M+, +P2W+ and +PT0.5S+, never +P+, +PT+, +P1H+
67
+ # (hours need the +T+) or +P1DT+. Each component is a count of whole units, only the seconds take a fraction.
68
+ #
69
+ # @return [Expression] a duration as ISO 8601 writes it: +P+, the years, months, weeks and days, then +T+ and
70
+ # the hours, minutes and seconds
71
+ def iso8601_duration = ISO8601_DURATION
72
+
73
+ # +Regexes.rfc3339_timestamp.whole+ matches +2026-11-21T14:30:05Z+ and +2026-11-21T14:30:05.123+05:30+, never
74
+ # one without seconds or an offset, or with +-0500+ (RFC 3339 wants the colon). The +T+ and +Z+ may be
75
+ # lowercase and the +T+ a space, as its §5.6 allows.
76
+ #
77
+ # @return [Expression] an internet timestamp (RFC 3339): a date and time to the second, and its offset
78
+ def rfc3339_timestamp = RFC3339_TIMESTAMP
79
+ end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Regexes
4
- VERSION = "0.0.0"
4
+ # The library's version.
5
+ VERSION = '0.1.0'
5
6
  end
data/lib/regexes.rb CHANGED
@@ -1,7 +1,130 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "regexes/version"
4
- require_relative "regexes/pattern"
3
+ require 'regexes/version'
4
+ require 'regexes/expression'
5
+ require 'regexes/character_class'
6
+ require 'regexes/ecma'
5
7
 
8
+ # Regular expressions named for what they match rather than what they are used for, so one is found and reused
9
+ # instead of written again inline. Each is a +Regexp+ ({Expression}) with the variations every expression
10
+ # allows — anchored, repeated, case-insensitive, captured — and a set of characters can be excluded and added
11
+ # to ({CharacterClass}). They chain:
12
+ #
13
+ # Regexes.lowercase_alphanumeric.excluded.one_or_more # => /[^a-z0-9]+/
14
+ # Regexes.lowercase_letters.excluded.one_or_more.leading # => /\A[^a-z]+/
15
+ # Regexes.sequence(Regexes.letters, Regexes.digits.at_least(2)) # => /[A-Za-z][0-9]{2,}/
16
+ #
17
+ # What lives here is a shape that recurs: a set of characters, a line break, a UUID, an address. The grammar
18
+ # of one format — a bounce address, a log line — belongs in a named constant in the code that owns the format,
19
+ # built from these. Each pattern is built once, frozen, as the library loads; a variation is built when asked
20
+ # for.
21
+ #
22
+ # The named patterns are defined by section in +regexes/patterns/+, loaded below in the order they build on
23
+ # each other; this file holds what composes them and what adds an application's own.
6
24
  module Regexes
25
+ extend self
26
+
27
+ # ── Composition ─────────────────────────────────────────────────────────────────────────────────────────
28
+
29
+ # +Regexes.sequence(Regexes.lowercase_letters, Regexes.word_characters.between(0, 23))+ is a handle: a
30
+ # lowercase letter, then up to 23 more.
31
+ #
32
+ # @param parts [Array<Expression>] what must match, one after another
33
+ # @return [Expression] each part, one after another
34
+ def sequence(*parts) = Expression.new(parts.map(&:embedded).join)
35
+
36
+ # +Regexes.either(Regexes.hyphen.one_or_more.leading, Regexes.hyphen.one_or_more.trailing)+ matches the
37
+ # hyphens at either end of a name.
38
+ #
39
+ # @param alternatives [Array<Expression>] what may match, any one of them
40
+ # @return [Expression] any one of the alternatives, as one unit
41
+ def either(*alternatives) = Expression.new("(?:#{alternatives.map(&:embedded).join('|')})", single: true)
42
+
43
+ # +Regexes.literal('.ns.cloudflare.com').trailing+ matches a Cloudflare nameserver, and +Regexes.literal('b+')+
44
+ # matches the text +b++, never +bb+: every character stands for itself. It is the safe way to put a value into
45
+ # a pattern, where interpolating it would let its dots and pluses match more than they say.
46
+ #
47
+ # @param text [String] the text to match, character for character
48
+ # @return [Expression] an expression matching exactly +text+
49
+ # @raise [ArgumentError] when +text+ is empty, which would match everywhere
50
+ def literal(text)
51
+ raise ArgumentError, 'literal(""): an empty literal matches everywhere' if text.empty?
52
+
53
+ Expression.new(Regexp.escape(text), single: text.length == 1)
54
+ end
55
+
56
+ # ── Registration ────────────────────────────────────────────────────────────────────────────────────────
57
+
58
+ # The lock around registration, so two threads can't register one name twice.
59
+ REGISTRATION = Mutex.new
60
+ # A name a pattern may be registered under: snake_case, as every named pattern is.
61
+ REGISTERED_NAME = /\A[a-z][a-z0-9]*(?:_[a-z0-9]+)*\z/
62
+ # An anchor at the start or end of a pattern's source, which a registered pattern leaves to its caller.
63
+ ANCHORED = /\A(?:\\A|\^)|(?<!\\)(?:\\[zZ]|\$)\z/
64
+ # The +Regexp+ options a registered pattern keeps; encoding flags are left to Ruby.
65
+ KEPT_OPTIONS = Regexp::IGNORECASE | Regexp::EXTENDED | Regexp::MULTILINE
66
+
67
+ # Adds a pattern of an application's own, to be named, varied and composed as the library's are:
68
+ #
69
+ # Regexes.register(:order_reference, /ORD-[0-9]{6}/)
70
+ # Regexes.order_reference.whole.match?('ORD-004211') # => true
71
+ #
72
+ # The pattern is the shape alone, unanchored: anchor it where it's used, with +.whole+ or +.leading+. A
73
+ # +Regexp+ or source +String+ is wrapped in a group, so an alternation in it stays one unit inside a sequence;
74
+ # an {Expression} is kept as it is.
75
+ #
76
+ # @param name [Symbol, String] the name to call it by: snake_case, and not a name +Regexes+ already answers to
77
+ # @param pattern [Regexp, String, Expression] what it matches
78
+ # @return [Expression] the registered pattern, frozen
79
+ # @raise [ArgumentError] when the name isn't snake_case or is taken, or the pattern is anchored
80
+ def register(name, pattern)
81
+ name = name.to_sym
82
+ expression = registrable(pattern)
83
+
84
+ REGISTRATION.synchronize do
85
+ check_registrable_name(name)
86
+ define_method(name) { expression }
87
+ (@registered ||= []) << name
88
+ end
89
+
90
+ expression
91
+ end
92
+
93
+ # @return [Array<Symbol>] the names registered with {.register}, in the order they were, frozen
94
+ def registered = (@registered || []).dup.freeze
95
+
96
+ private
97
+
98
+ # @param name [Symbol] a name to register a pattern under
99
+ # @return [void]
100
+ # @raise [ArgumentError] when it isn't snake_case, or +Regexes+ already answers to it
101
+ def check_registrable_name(name)
102
+ raise ArgumentError, "register(#{name.inspect}): name a pattern in snake_case" unless REGISTERED_NAME.match?(name)
103
+ raise ArgumentError, "register(#{name.inspect}): Regexes.#{name} already exists" if respond_to?(name, true)
104
+ end
105
+
106
+ # @param pattern [Regexp, String, Expression] a pattern to register
107
+ # @return [Expression] it, as an expression
108
+ # @raise [ArgumentError] when it is anchored, or of another type
109
+ def registrable(pattern)
110
+ source = pattern.is_a?(Regexp) ? pattern.source : pattern
111
+ raise ArgumentError, "register: #{pattern.inspect} is not a Regexp or String" unless source.is_a?(String)
112
+ raise ArgumentError, "register: #{pattern.inspect} is anchored; register the shape and anchor it where used" if
113
+ ANCHORED.match?(source)
114
+
115
+ return pattern if pattern.is_a?(Expression)
116
+
117
+ options = pattern.is_a?(Regexp) ? pattern.options & KEPT_OPTIONS : 0
118
+ Expression.new("(?:#{source}#{"\n" if options.anybits?(Regexp::EXTENDED)})", single: true, options:)
119
+ end
7
120
  end
121
+
122
+ require 'regexes/patterns/sets'
123
+ require 'regexes/patterns/breaks'
124
+ require 'regexes/patterns/numbers'
125
+ require 'regexes/patterns/identifiers'
126
+ require 'regexes/patterns/times'
127
+ require 'regexes/patterns/network'
128
+ require 'regexes/patterns/mail'
129
+ require 'regexes/patterns/codes'
130
+ require 'regexes/patterns/text'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: regexes
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.0
4
+ version: 0.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sebastian Scholl
@@ -9,18 +9,41 @@ bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies: []
12
+ description: |
13
+ Regexes is a library of frozen Regexp objects named for what they match (letters, digits, UUIDs,
14
+ ISO 8601 times, domain names, email addresses), each chaining the variations every expression allows:
15
+ anchored, repeated, case-insensitive, and for sets of characters, excluded and extended. No dependencies.
16
+ email:
17
+ - sebscholl@gmail.com
12
18
  executables: []
13
19
  extensions: []
14
20
  extra_rdoc_files: []
15
21
  files:
22
+ - CHANGELOG.md
16
23
  - LICENSE.txt
17
24
  - README.md
18
25
  - lib/regexes.rb
19
- - lib/regexes/pattern.rb
26
+ - lib/regexes/character_class.rb
27
+ - lib/regexes/ecma.rb
28
+ - lib/regexes/expression.rb
29
+ - lib/regexes/patterns/breaks.rb
30
+ - lib/regexes/patterns/codes.rb
31
+ - lib/regexes/patterns/identifiers.rb
32
+ - lib/regexes/patterns/mail.rb
33
+ - lib/regexes/patterns/network.rb
34
+ - lib/regexes/patterns/numbers.rb
35
+ - lib/regexes/patterns/sets.rb
36
+ - lib/regexes/patterns/text.rb
37
+ - lib/regexes/patterns/times.rb
20
38
  - lib/regexes/version.rb
39
+ homepage: https://github.com/sebscholl-labs/regexes
21
40
  licenses:
22
41
  - MIT
23
42
  metadata:
43
+ bug_tracker_uri: https://github.com/sebscholl-labs/regexes/issues
44
+ changelog_uri: https://github.com/sebscholl-labs/regexes/blob/main/gem/CHANGELOG.md
45
+ documentation_uri: https://sebscholl-labs.github.io/regexes/
46
+ source_code_uri: https://github.com/sebscholl-labs/regexes/tree/main/gem
24
47
  rubygems_mfa_required: 'true'
25
48
  rdoc_options: []
26
49
  require_paths:
@@ -29,14 +52,15 @@ required_ruby_version: !ruby/object:Gem::Requirement
29
52
  requirements:
30
53
  - - ">="
31
54
  - !ruby/object:Gem::Version
32
- version: '3.1'
55
+ version: '4.0'
33
56
  required_rubygems_version: !ruby/object:Gem::Requirement
34
57
  requirements:
35
58
  - - ">="
36
59
  - !ruby/object:Gem::Version
37
60
  version: '0'
38
61
  requirements: []
39
- rubygems_version: 3.6.9
62
+ rubygems_version: 4.0.20
40
63
  specification_version: 4
41
- summary: Regexes (work in progress).
64
+ summary: 'Named, tested regular expressions for Ruby: frozen Regexps for UUIDs, IP
65
+ addresses, times and more, with chainable anchors, repetition and captures.'
42
66
  test_files: []