Ruby / Foundations: values, methods, text, and valid objects / Lesson 7
Regular expressions and input boundaries
Validate Ruby input with anchored regular expressions and captures.
On this page
Lesson goals
- Distinguish whole-string matching from substring search.
- Check a match before reading captures.
- Design bounded whole-input patterns and distinguish lexical shape from domain validity.
- Handle MatchData, absent captures and literal dynamic fragments deliberately.
Define the pattern contract
A regular expression describes a pattern to search for in text. Before writing one, define whether the entire input must match or whether a matching substring is sufficient. Input validation also needs a size and encoding policy. A successful pattern match establishes only the properties expressed in that pattern; it does not automatically make the value safe for another output or command context.
Anchor the whole input
The anchors \A and \z describe the beginning and end of the whole string in Ruby regular expressions. The example accepts a small lowercase identifier and rejects the same letters followed by a digit. The pattern is deliberately a synthetic rule, not a universal username policy. Choose an explicit allowed character set and length appropriate to the real domain.
pattern = /\A[a-z]{2,4}\z/
puts pattern.match?("ruby")
puts pattern.match?("ruby1")
true
false
Only the complete lowercase identifier matches.
Read a capture
MatchData exposes captures when a pattern matches; a failed match returns nil. Check the result before reading a capture. The example extracts the numeric part of a fixed record and prints it as text. If that text must become a number, use a conversion policy that rejects malformed or out-of-range values rather than assuming a capture alone proves the domain value is valid.
match = /\Aitem-(\d+)\z/.match("item-42")
puts match[1] if match
42
The capture contains the digits as text.
Keep patterns bounded
Anchoring matters because a substring search can find a valid-looking part inside otherwise invalid input. Keep patterns readable and avoid constructing regular expressions directly from untrusted fragments without escaping and a clear policy. Limit input size before expensive processing. If a rule is easier to understand as several simple checks, prefer that composition over a dense expression that is difficult to review.
Test matches and rejections
Test a valid input, empty input, an invalid prefix and suffix, and a value at the documented length boundary. Include multibyte text when the domain accepts it and verify that the encoding is valid before applying assumptions about characters. Assert both match and rejection cases. Preserve the original failing input as a synthetic regression case when repairing a pattern.
Translate input policy into a pattern
A regular expression is one part of an input contract. Decide the accepted type and encoding, maximum size, allowed characters, separators and length before writing the pattern. Distinguish a search for a fragment from validation of an entire field. For example, an identifier policy might allow two uppercase ASCII letters followed by three digits, while a log search might intentionally find that sequence within a longer line. Those are different questions even if they share the same character classes.
Use small synthetic strings to record the expected positive and negative decisions. A pattern proves only its stated lexical property: a well-formed code may still refer to no record or be unauthorized for the caller. Likewise, a match does not make text safe for SQL, HTML, shell commands or other output contexts. Apply the relevant API and escaping or parameterization at that separate boundary. Preserve only the minimum diagnostic data needed when rejected input can be sensitive.
Choose boundaries and character sets explicitly
An unanchored pattern may match a substring surrounded by invalid data. In Ruby, \A and \z mark the beginning and end of the whole string. The anchors ^ and $ instead match line boundaries, which can allow a matching line inside a longer multiline value. A final newline deserves its own test: a validator that must consume the entire input should reject it unless the contract explicitly permits it. Use bounded repetition such as {2,4} when the permitted size is bounded and test both endpoints and their neighbors.
Choose character classes based on the actual policy, not a label such as letters or digits alone. An ASCII-only class is a different decision from accepting text in multiple scripts. Validate that the incoming byte sequence is valid under the accepted encoding before making assumptions about text. Byte limits, character counts and user-perceived graphemes are different units; a short byte slice can split a multibyte character. Define any normalization before matching and preserve the original where identity or provenance requires it.
Treat a match as an optional structured result
Regexp#match returns MatchData on success and nil on failure. Store the result locally and test it before reading numbered or named captures. A capture is text, not automatically a validated domain number. If a captured quantity must be between 1 and 50, first constrain its lexical form, convert with the intended base and failure handling, then check the range. A successful match for 99 can be syntactically valid yet fail the business rule.
Use match? for a Boolean decision when captures are unnecessary; use match when the caller needs MatchData. Named captures can make a multi-field format easier to review, while noncapturing groups can group alternatives without adding an unwanted numbered capture. Document which groups are required and what an optional group means when absent. Avoid relying on an earlier implicit match state after unrelated operations; keeping the MatchData object next to the validation makes the source of each extracted value clear.
Keep dynamic fragments literal and processing bounded
If the caller supplies text to search literally, use Regexp.escape before inserting it into a larger regular expression. Without escaping, characters such as a dot or plus can change the pattern’s meaning. Escaping a fragment does not itself anchor the whole expression or validate the business value; decide those rules separately. If users are actually allowed to supply pattern syntax, that is a different, explicitly designed interface with different validation and resource controls.
Limit input size before matching and prefer readable patterns with bounded repetition over ambiguous constructions that are hard to review. Ruby 3.3 documents regular-expression timeout controls, but a timeout is a separate operational safeguard, not a proof that a pattern is safe or that a particular runtime behaved as expected. Establish the timeout and error policy for the target environment, and test representative adverse inputs in isolation. Do not claim timing measurements or production protection from a static example.
Test boundaries, captures and limitations
Build a table with valid minimum and maximum lengths, one shorter and one longer value, empty input, invalid prefix and suffix, and an embedded or final newline. Add a permitted or rejected multibyte example according to the actual character policy. For a capture, test a match and a miss, confirm that no indexing occurs on nil, and check the converted value’s domain boundary. If dynamic literal text is allowed, test a metacharacter as data as well as a nearby nonmatch.
These examples use synthetic Ruby source and do not query a service or inspect private records. Ruby was unavailable in the authoring environment, so expected output is reasoned from the Ruby 3.3 documentation and is not an execution transcript. Run the snippets in an isolated compatible interpreter, then test the application’s real encoding, limits and error reporting separately. A passed illustrative example establishes neither runtime performance nor safety in an unrelated output context.
20 worked examples
1. Substring search
Problem: Find a fixed fragment inside surrounding text.
- The unanchored pattern can begin after the first character.
- The letters cat occur inside the longer input.
p(/cat/.match?('scatter'))
true
Why this result follows: A substring search intentionally allows surrounding text.
2. Whole-field validation
Problem: Reject surrounding text for an exact field.
- The anchors require the entire string to be cat.
- The longer input contains extra characters and fails.
p(/\Acat\z/.match?('scatter'))
false
Why this result follows: Whole-string anchors enforce the exact field boundary.
3. Line versus string anchors
Problem: Compare a matching second line with the whole input.
- Line anchors can match OK after a newline.
- String anchors cannot ignore the preceding line.
s = "bad\nOK"
p(/^OK$/.match?(s))
p(/\AOK\z/.match?(s))
true
false
Why this result follows: A line match is not a whole-input match.
4. Final newline
Problem: Reject a newline after an otherwise valid fixed value.
- The literal OK matches the first two characters.
- The final newline prevents \z from following immediately.
p(/\AOK\z/.match?("OK\n"))
false
Why this result follows: The end anchor requires the actual end of the string.
5. Length boundary
Problem: Compare values at the lower and upper length limits.
- The rule allows two through four lowercase ASCII letters.
- Both ab and abcd satisfy those limits.
re = /\A[a-z]{2,4}\z/
p re.match?('ab')
p re.match?('abcd')
true
true
Why this result follows: Both inclusive repetition endpoints are accepted.
6. Locate a substring match
Problem: Find the matched fragment and its start in a longer string.
- The unanchored pattern finds cat starting at character index 1.
- MatchData exposes both the start and the matched text.
m = /cat/.match('scatter')
p m.begin(0) if m
p m[0] if m
1
"cat"
Why this result follows: The offset locates the match without asserting whole-field validity.
7. ASCII character policy
Problem: Reject a non-ASCII letter under an ASCII-only rule.
- The class [a-z] contains the specified ASCII lowercase range.
- The accented letter is outside that range.
p(/\A[a-z]+\z/.match?('café'))
false
Why this result follows: The explicit class expresses a narrow character policy.
8. Named captures
Problem: Extract two fields from a matching code.
- The pattern captures the uppercase prefix and two digits by name.
- The matched record exposes both captures as strings.
m = /\A(?<area>[A-Z]{2})-(?<num>[0-9]{2})\z/.match('AB-07')
puts m[:area] if m
puts m[:num] if m
AB
07
Why this result follows: Named captures make the two extracted text fields explicit.
9. Failed match handling
Problem: Avoid indexing a nil result for a malformed code.
- The input contains letters where the pattern expects digits.
- match returns nil, so the guard prints invalid instead of indexing it.
m = /\Aref-([0-9]+)\z/.match('ref-x')
puts(m ? m[1] : 'invalid')
invalid
Why this result follows: The guard handles the absence of MatchData.
10. Syntactic capture, rejected range
Problem: Reject a well-formed quantity outside the allowed domain.
- The digits capture matches the text 75.
- After conversion, 75 is outside the declared range 1 through 50.
m = /\Aqty-([0-9]{1,2})\z/.match('qty-75')
n = Integer(m[1], 10) if m
puts(n && (1..50).cover?(n) ? 'accept' : 'reject')
reject
Why this result follows: A lexical capture must still pass the domain range check.
11. Transform matched fragments
Problem: Bracket each digit run while preserving surrounding text.
- gsub finds each run of one or more ASCII digits.
- The block receives each matched fragment and returns its replacement.
s = 'A1 B22'
result = s.gsub(/[0-9]+/) { |digits| "[#{digits}]" }
puts result
A[1] B[22]
Why this result follows: The substitution transforms matches rather than validating the entire input.
12. Optional capture absent
Problem: Inspect an optional suffix that was not supplied.
- The required prefix and digits match the input.
- The optional capture did not participate and is nil.
m = /\Aref-([0-9]+)(?:-([A-Z]))?\z/.match('ref-3')
p m[1]
p m[2]
"3"
nil
Why this result follows: An optional group can be absent even in a successful match.
13. Noncapturing alternative
Problem: Group alternatives without adding a capture.
- The noncapturing group selects either red or blue.
- Only the numeric group is available as capture 1.
m = /\A(?:red|blue)-([0-9])\z/.match('blue-4')
p m.captures
["4"]
Why this result follows: Grouping alternatives need not change capture numbering.
14. Literal plus from input
Problem: Escape a user fragment intended as literal text.
- Regexp.escape quotes the plus metacharacter.
- The anchored constructed pattern matches the literal fragment.
fragment = Regexp.escape('a+b')
re = Regexp.new("\\A#{fragment}\\z")
p re.match?('a+b')
p re.match?('ab')
true
false
Why this result follows: Escaping prevents the plus from becoming a repetition operator.
15. Boolean match without capture
Problem: Check a fixed prefix without requesting MatchData.
- The pattern is a search for the literal prefix.
- match? returns a Boolean result for this query.
p(/\Alog:/.match?('log: ready'))
true
Why this result follows: The caller needs only the Boolean decision.
16. Explicit optional delimiter
Problem: Accept both allowed forms while rejecting another separator.
- The optional hyphen permits AB12 and AB-12.
- An underscore is not one of the permitted forms.
re = /\AAB-?[0-9]{2}\z/
p re.match?('AB12')
p re.match?('AB-12')
p re.match?('AB_12')
true
true
false
Why this result follows: The optional quantifier applies only to the hyphen.
17. Bound input before matching
Problem: Reject an overlength value before applying the grammar.
- The policy allows at most four bytes for this ASCII fixture.
- The five-byte input takes the too-long branch before matching.
s = 'abcde'
if s.bytesize > 4
puts 'too long'
else
puts(/\A[a-z]+\z/.match?(s))
end
too long
Why this result follows: The size boundary is independent of the regex result.
18. Invalid encoding first
Problem: Reject invalid UTF-8 bytes before evaluating a pattern.
- The byte FF is not a valid UTF-8 sequence.
- The guard reports invalid encoding without calling match?.
s = [0xFF].pack('C').force_encoding('UTF-8')
if s.valid_encoding?
p(/\A[a-z]+\z/.match?(s))
else
puts 'invalid encoding'
end
invalid encoding
Why this result follows: Encoding validation protects the stated text boundary.
19. Capture remains text
Problem: Show that leading zero remains in a capture.
- The digits in code-007 match the capture.
- MatchData returns the captured characters as a String.
m = /\Acode-([0-9]{3})\z/.match('code-007')
p m[1] if m
"007"
Why this result follows: Extraction does not silently convert the capture to integer 7.
20. Use a local match result
Problem: Read captures from two independent match objects.
- Each match call returns its own MatchData.
- The stored objects retain their respective captures.
re = /\A([A-Z])-([0-9])\z/
a = re.match('A-1')
b = re.match('B-2')
puts a[1] if a
puts b[1] if b
A
B
Why this result follows: Local MatchData makes each capture source explicit.
Common errors and fixes
Invalid surrounding text is accepted
- Why it happens
- The pattern matched only a substring.
- How to fix it
- Anchor the complete input when required.
- Prevent it next time
- Test invalid prefixes and suffixes.
A capture access fails
- Why it happens
- The match result was nil.
- How to fix it
- Check the result before accessing captures.
- Prevent it next time
- Test a nonmatching input.
A valid pattern match bypasses validation
- Why it happens
- The pattern did not express the domain range.
- How to fix it
- Validate the converted value separately.
- Prevent it next time
- Test semantic boundaries.
20 practice exercises
1. Does ruby1 match the first pattern?
Show hint
Check the final character against the class and the end anchor.
Show worked solution
No. The final digit is not allowed, and the whole-string anchors prevent a partial match.
The pattern accepts two to four lowercase ASCII letters and requires the whole string. ruby1 has a forbidden fifth character, so the anchors prevent accepting ruby as a partial match.
Check your solution
- The digit is identified as outside the permitted class.
- The complete input is rejected rather than partially matched.
2. Why check match before accessing a capture?
Show hint
Consider the type of the result when no pattern matches.
Show worked solution
A failed match returns nil, which does not contain capture data.
match returns nil for a nonmatch, not a MatchData object. Guard the local result before reading a capture and test both a valid record and a malformed one.
Check your solution
- A failed match is handled without indexing nil.
- A successful match exposes the expected captured text.
3. A field requires exactly two uppercase ASCII letters and three digits. Write a whole-string pattern and classify AB123, xAB123 and AB123x.
Show hint
Anchor both ends and bound each class.
Show worked solution
Use /\A[A-Z]{2}[0-9]{3}\z/. AB123 matches; the prefixed and suffixed inputs fail because the complete string must satisfy the grammar. This checks shape, not record existence.
Check your solution
- AB123 is accepted lexically.
- Both surrounding-text cases are rejected.
4. A protocol accepts exactly OK optionally followed by one LF terminator, but rejects extra lines or two terminators. Design full-input validation and a four-case test.
Show hint
Model the optional terminator explicitly inside whole-string anchors.
Show worked solution
Use /\AOK\n?\z/ for this declared byte-level line policy. Accept OK and OK followed by one LF; reject a leading line and OK followed by two LFs. Do not silently strip arbitrary whitespace because that would broaden the contract.
Check your solution
- OK with zero or one LF is accepted.
- A leading line and two trailing LFs are rejected.
5. A code allows three to six lowercase ASCII letters. Build a boundary test table including empty, two, three, six and seven letters.
Show hint
Include both accepted endpoints and their neighbors.
Show worked solution
Use a bounded full-string rule such as /\A[a-z]{3,6}\z/. Reject empty, two and seven letters; accept three and six. Include an uppercase value as a separate character-policy rejection.
Check your solution
- Three and six lowercase letters are accepted.
- Empty, two, seven and uppercase inputs are rejected.
6. A loop matches ref-3 successfully, then fails to match ref-x but prints the earlier capture as if it belonged to the second input. Diagnose the stale-result bug and design a repair.
Show hint
Associate a fresh MatchData result with each input and branch on that result.
Show worked solution
Assign the result of each match to a local for that iteration and read its capture only when that result is non-nil. Report ref-3 with capture "3" and ref-x as invalid; never reuse the previous successful capture for the failed input.
Check your solution
- The first input reports capture "3".
- The second reports invalid and does not reuse "3".
7. A captured quantity permits digits but the domain requires 1 through 20. Classify qty-00, qty-20 and qty-21 after matching.
Show hint
Parsing success and permitted range are separate.
Show worked solution
Convert the captured digits with the intended decimal rule, then check 1..20. Reject 00 as zero, accept 20 and reject 21; all can have valid digit shape while producing different domain decisions.
Check your solution
- Only qty-20 is accepted by the range.
- Zero and 21 are rejected after lexical matching.
8. A user enters a.b as a literal search fragment. Design a pattern construction and tests for a.b and axb.
Show hint
A dot is otherwise a regex wildcard.
Show worked solution
Escape the fragment with Regexp.escape before building the pattern. Confirm a.b is matched literally and axb is not; add anchors only if the application requires the entire field rather than a substring.
Check your solution
- The literal dot matches a.b.
- The escaped dot does not match x.
9. A two-field code has a region and a numeric serial. Design named captures and show what must be validated after matching AB-05.
Show hint
Captured digits remain text.
Show worked solution
Use a full-string pattern with named region and serial groups, such as two uppercase letters and two digits. On a successful match retrieve "AB" and "05", convert the serial with an explicit decimal policy, then validate its permitted domain range.
Check your solution
- The captures are AB and 05 as strings.
- Numeric conversion and range are checked separately.
10. A code permits an optional suffix -X. Specify expected captures for item-7 and item-7-X, including the absent suffix.
Show hint
A successful match can contain a nil optional group.
Show worked solution
Match the complete prefix, digits and optional suffix, storing the optional X in its own capture. The first input yields digit text "7" and nil suffix; the second yields "7" and "X". Guard the MatchData before reading either.
Check your solution
- The absent suffix is nil, not a failed whole match.
- The supplied suffix is captured as X.
11. A pattern ((red|blue)-([0-9]+)) exposes three numbered captures, but callers need the whole code and the serial by stable names. Redesign its capture contract and test both colors.
Show hint
Use named captures for required fields and noncapturing grouping where a group is structural.
Show worked solution
Capture the whole code as code and the digit sequence as serial, using a noncapturing color alternative inside the code group. Test red-2 and blue-17 and assert named code and serial values; callers no longer depend on incidental numbered group positions.
Check your solution
- Both colors yield the complete named code.
- The named serial yields "2" and "17" respectively.
12. An API accepts UTF-8 text up to 40 bytes before pattern validation. Design processing for invalid bytes and a 41-byte valid input.
Show hint
Encoding validity and byte length precede lexical matching.
Show worked solution
Check that the input is a string with the accepted encoding and valid bytes, then reject anything over 40 bytes before regex matching. Test valid 40-byte input, valid 41-byte input and invalid UTF-8 independently; report bounded error categories.
Check your solution
- Invalid bytes do not reach regex matching.
- A valid 41-byte input is rejected for size.
13. A pattern uses an unbounded nested repetition on externally supplied text. Propose a review and operational test plan without claiming measured performance.
Show hint
A bounded input and simpler grammar reduce the space to review.
Show worked solution
Replace the pattern with a clearer bounded expression where it represents the same allowed language, set an appropriate size and timeout policy, and test representative adverse inputs in an isolated target environment. Record observed limits rather than inferring a benchmark from source.
Check your solution
- The plan includes input limits and timeout handling.
- No unmeasured runtime claim is made.
14. A well-formed code passes its regex but points to a record another user owns. Define the remaining checks.
Show hint
Shape does not establish existence or authorization.
Show worked solution
Look up the code in the authoritative data source and evaluate the caller’s permission for the requested action. Apply the application’s disclosure policy to missing and denied outcomes; do not treat a regex match as permission.
Check your solution
- A valid-looking missing code is not treated as an existing record.
- An existing record still requires an authorization check.
15. A user value contains a newline after a valid code. Explain why testing only a visible valid example misses this case.
Show hint
The final byte can alter the whole-input decision.
Show worked solution
Add an explicit code followed by newline to the negative test set and use whole-string anchors if the policy forbids it. Verify the valid code still matches and that no trimming occurs unless the input contract authorizes it.
Check your solution
- The plain code matches.
- The same code with a trailing newline is rejected under the stated policy.
16. A user-provided regex fragment is meant to be literal, but the interface also supports whole-field validation. Specify both construction steps and tests.
Show hint
Escaping and anchoring solve different problems.
Show worked solution
Escape the fragment with Regexp.escape, then place the escaped fragment between whole-string anchors when constructing the pattern. Test a metacharacter-containing literal, an altered character and a valid literal with a prefix; only the exact literal should match.
Check your solution
- Metacharacters are treated literally.
- Extra prefix text fails the whole-field rule.
17. A quantity capture can be empty if the pattern uses * instead of +. Explain the consequence and repair the grammar for one or more digits.
Show hint
The star quantifier permits zero repetitions.
Show worked solution
Replace [0-9]* with [0-9]+ when at least one digit is required, keeping whole-input anchors. Test an empty suffix as rejected and a one-digit suffix as accepted before conversion.
Check your solution
- An empty numeric suffix is rejected.
- A one-digit suffix is accepted lexically.
18. A pattern accepts two uppercase ASCII letters, but the product also needs accented names. Explain the mismatch and plan verification without guessing a universal name grammar.
Show hint
The class expresses a narrow ASCII rule.
Show worked solution
Confirm the supported scripts and normalization with the product owner, select a documented Unicode-aware policy and validate encodings, then test representative accented and decomposed inputs. Do not silently widen an identifier grammar without defining its consequences.
Check your solution
- The existing ASCII rule is identified as narrower than the requirement.
- The plan includes representative Unicode and normalization tests.
19. A capture is stored as "007", but downstream code immediately converts it to 7. Explain a case where this loses meaning and define a contract.
Show hint
Textual identifiers and numeric quantities have different semantics.
Show worked solution
If leading zeros are part of an identifier, keep "007" as text and compare under the identifier policy; converting to 7 loses its representation. If it is a quantity, define whether zeros are accepted and test the conversion and range separately.
Check your solution
- The identifier path preserves "007".
- The quantity path states conversion and range rules.
20. Build a regression table for a full-field code parser with two letters, a hyphen and two digits. Include a valid but unauthorized code and specify where each decision belongs.
Show hint
Lexical validation and authorization have separate owners.
Show worked solution
Include a valid authorized code, invalid prefix, trailing newline, malformed digits and a well-formed unauthorized code. Reject malformed entries at the lexical boundary and evaluate the last code at the separate lookup and authorization boundary.
Check your solution
- Malformed inputs fail lexical validation.
- The well-formed unauthorized input reaches and fails authorization.
Key takeaways
- Define whether the whole input must match.
- Validate captures against domain rules.
- Whole-string and line anchors have different boundaries.
- A capture is text and may still need conversion and range validation.
- Limit and validate input before treating a match as evidence.