HackerRank: Validating Strings with Regex
How regex validation works for HackerRank-style string problems: anchoring, Unicode character classes, copy-paste pitfalls, and when plain string methods are the better choice.
People who search for a HackerRank solution to a string validation problem usually want a pattern that passes the hidden test cases. This review helps you judge whether a regular expression is the right tool for that job. It explains what validation does to the input and what can break when a solution is copied or shared. No confirmed details of a specific HackerRank problem statement, test set or judge configuration were available for this review. The examples below are therefore illustrative, and you should check them against the exact statement you are solving.
Is a regex approach suitable for this kind of problem?
A regular expression is a good fit when the rule describes the shape of the whole string. Examples include a fixed length, an allowed set of characters, a required prefix or a sequence of ordered segments. The main benefit is that one declarative pattern encodes the rule and can be run against any number of inputs. The decisive tradeoff is that a pattern can look correct while accepting more than intended. Partial matching, Unicode-aware character classes and trailing newlines are easy to overlook, and these mistakes produce no error. The submission simply passes some cases and fails others.
Plain string methods or ordinary code are often preferable in three situations. The first is when the rule is a single property, such as a length limit or a test that every character is a digit. The second is when the rule involves a numeric range, which regex expresses awkwardly. The third is when the rule requires counting across the string, such as a minimum number of uppercase letters or a ban on repeated characters. In those cases, a short pattern for the overall shape combined with a few explicit checks is usually easier to read and debug than one long pattern built from lookaheads.
What regex validation actually changes
Validation is not a text transformation in the way that reversing, mirroring or restyling text is. It leaves the stored characters unchanged and returns a decision, typically printed as a value such as True/False or YES/NO for each input line. What does affect the outcome is the code before the match: how input is read, whether the trailing newline is stripped, and which matching function is called. Some terms are also ambiguous here. In Python, re.match does not mean the whole string matches. It means a match is anchored at the start of the string and may stop partway through.
| Call or construct | What must match | Common surprise |
| re.match(p, s) | A prefix of s, starting at position 0 | Extra characters after the match are ignored |
| re.search(p, s) | Any substring of s | Accepts invalid strings that merely contain a valid part |
| re.fullmatch(p, s) | The entire string s | None; this is usually the intended check |
| ^...$ with re.match | Start of s to end of s, or to just before a final newline | A string ending in a newline can still pass |
| \A...\Z | Absolute start to absolute end | None, but easy to confuse with ^ and $ |
The following example uses a rule chosen only for illustration: exactly ten ASCII digits, with a first digit of 7, 8 or 9. The printed results show how fullmatch treats near-miss inputs.
import re
# Illustrative rule: exactly 10 ASCII digits, first digit 7, 8 or 9
pattern = re.compile(r"[789][0-9]{9}")
for raw in ["9876543210", "98765432101", "9876543210\n", "987654321"]:
ok = pattern.fullmatch(raw) is not None
print(repr(raw), ok)
# '9876543210' True
# '98765432101' False
# '9876543210\n' False
# '987654321' False
The same rule written with the wrong call or anchors accepts inputs it should reject:
import re
re.match(r"[789]\d{9}", "98765432101") # matches: only the first 10 characters are checked
re.match(r"^[789]\d{9}$", "9876543210\n") # matches: $ also matches just before a trailing newline
re.fullmatch(r"[789]\d{9}", "9876543210\n") # None: the newline is part of the string
Calling input().strip() before validating removes the trailing newline and any surrounding spaces. Whether stripping is correct depends on the problem. If leading or trailing spaces should make an input invalid, stripping them hides the error.
Unicode character classes
For str patterns in Python 3, \d matches any Unicode decimal digit, including Arabic-Indic digits. Likewise, \w matches letters from many scripts, and \s matches a range of Unicode whitespace characters. If a problem means ASCII digits only, write [0-9] or pass the re.ASCII flag. String methods have similar behavior. str.isdigit returns True for characters such as superscript two. str.isdecimal is stricter but still accepts non-ASCII decimal digits. Adding a str.isascii check restricts the input to ASCII.
import re
s = "٣٤٥" # Arabic-Indic digits
print(bool(re.fullmatch(r"\d+", s))) # True
print(bool(re.fullmatch(r"\d+", s, re.ASCII))) # False
print(bool(re.fullmatch(r"[0-9]+", s))) # False
print("²".isdigit(), "²".isdecimal()) # True False
Other languages behave differently. In JavaScript, \d always means [0-9]. JavaScript has no fullmatch, so you need ^ and $, and without the m flag the $ anchor matches only at the true end of the string. In Java, \d is ASCII-only unless UNICODE_CHARACTER_CLASS is enabled, and String.matches requires the whole string to match. A pattern ported between languages can therefore change what it accepts even though its text is unchanged.
Lengths, combining marks and emoji
A quantifier such as {10} counts code points, not the characters a reader perceives. An accented letter like é can be stored as one code point (U+00E9) or as a plain e followed by a combining acute accent (U+0301). Many emoji, including family and flag sequences, consist of several code points. If a rule says a string must contain a certain number of characters and the input might include such text, decide whether the rule means code points or visible characters. Normalizing with unicodedata.normalize("NFC", s) merges most precomposed and decomposed accent forms, but it does not collapse multi-code-point emoji. Whether a given HackerRank test set contains such input is not known from the available evidence.
Will the solution survive copying and sharing?
A regex solution is plain source code, so the risks come from the path it travels between where it was written and where it is submitted. Text copied from web pages, chat apps, word processors or rendered Markdown can change in ways that are invisible on screen:
- Curly quotation marks replace straight quotes, which causes a syntax error.
- Non-breaking spaces or mixed tabs and spaces break Python indentation or parsing.
- Zero-width characters inside a pattern silently change what the pattern matches.
- Letters from other scripts that look like Latin letters, such as Cyrillic а, make a literal in the pattern fail to match.
- Markdown or chat formatting can consume backslashes or asterisks, which changes the pattern itself.
Before submitting a pasted solution, scan it for non-ASCII characters. The script below flags every line that contains one. It will also flag string literals that are meant to contain non-ASCII text, so treat its output as a list of lines to inspect rather than a list of errors.
with open("solution.py", encoding="utf-8") as f:
for n, line in enumerate(f, 1):
if not line.isascii():
print(n, ascii(line))
Dense patterns are hard for anyone to read and harder still when read aloud symbol by symbol. How a particular screen reader announces the punctuation in a pattern depends on its verbosity settings. No scoped test of a specific screen reader was available for this review. In Python, re.VERBOSE allows whitespace and comments inside a pattern, which makes the rule easier to review. When you share a solution, add one sentence that states the rule in words. That plain-text description lets reviewers, search tools and assistive technology users confirm the intent without decoding the pattern.
import re
pattern = re.compile(r"""
[789] # first digit must be 7, 8 or 9
[0-9]{9} # followed by exactly nine ASCII digits
""", re.VERBOSE)
Online regex testers are convenient for experimenting, but their results apply only to the regex flavor selected. A pattern tested under a PCRE or JavaScript setting can behave differently in Python, as the anchoring and \d differences above show. Choose the flavor that matches your submission language. Do not assume anything about how a tester stores or handles pasted input. No evidence about any tester's data practices was reviewed, so avoid pasting sensitive real data into one.
Gaps in this review
- The exact HackerRank problem statement, input format and constraints were not available, so the example rule is illustrative only.
- The hidden test cases are unknown, including whether they contain non-ASCII digits, combining marks, emoji or trailing whitespace.
- The language and runtime versions used by the judge were not confirmed.
- No rendering or screen reader test was performed for any named editor, browser or assistive technology.
Bottom line
Use a regular expression when the rule describes the whole shape of a string. Match the full string explicitly, and spell out ASCII character ranges when the problem means ASCII. Use plain string methods or ordinary code for single-property checks, numeric ranges and counting rules. Before submitting or sharing, check pasted code for invisible or lookalike characters, and pair any non-trivial pattern with a plain-language statement of the rule it enforces.