Skip to content

Replace recursive regex in PhoneNumberUtil.normalize() with linear scan - #4094

Open
reginaldalfret wants to merge 1 commit into
google:masterfrom
reginaldalfret:fix/normalize-replace-regex-with-linear-scan
Open

reginaldalfret wants to merge 1 commit into
google:masterfrom
reginaldalfret:fix/normalize-replace-regex-with-linear-scan

Conversation

@reginaldalfret

Copy link
Copy Markdown

Problem

In PR #4017, VALID_ALPHA_PHONE_PATTERN ((?:.?[A-Za-z]){3}.) was replaced with hasAtLeastThreeAlphaChars() in PhoneNumberUtil.isAlphaNumber() because the non-greedy regex causes recursive stack frame evaluation in java.util.regex, resulting in StackOverflowError on long numeric input strings.

However, PhoneNumberUtil.normalize(StringBuilder) still called:
java Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number); if (m.matches()) {
leaving
ormalize() vulnerable to the exact same StackOverflowError when called with long numeric inputs (e.g. ~1,684+ digits), and leaving VALID_ALPHA_PHONE_PATTERN in the codebase solely for that one call.

Solution

  1. Replace VALID_ALPHA_PHONE_PATTERN.matcher(number).matches() with hasAtLeastThreeAlphaChars(number) in PhoneNumberUtil.normalize(StringBuilder).
  2. Delete the now-unused VALID_ALPHA_PHONE_PATTERN constant from PhoneNumberUtil.java.
  3. Add regression test estNormaliseLongNumericInputDoesNotThrow in PhoneNumberUtilTest.java.
  4. Update pending_code_changes.txt.

Verification

  • Added estNormaliseLongNumericInputDoesNotThrow testing normalization of 5,000 digits without StackOverflowError.
  • Ran mvn -pl java/libphonenumber test: all 285 tests passed with 0 failures, 0 errors.

PR google#4017 replaced VALID_ALPHA_PHONE_PATTERN with hasAtLeastThreeAlphaChars()
in PhoneNumberUtil.isAlphaNumber() to eliminate StackOverflowError caused by
recursive evaluation on long numeric inputs in java.util.regex. However,
PhoneNumberUtil.normalize(StringBuilder) still called
VALID_ALPHA_PHONE_PATTERN.matcher(number).matches(), leaving normalize()
vulnerable to the same recursion failure and leaving VALID_ALPHA_PHONE_PATTERN
in the codebase solely for that call.

This commit updates normalize(StringBuilder) to use hasAtLeastThreeAlphaChars(number)
and removes the unused VALID_ALPHA_PHONE_PATTERN, fully eliminating the pattern
and preventing StackOverflowError on long inputs.

Also adds a regression test and updates pending_code_changes.txt.

Signed-off-by: reginaldalfret <reginaldalfret@gmail.com>
@reginaldalfret
reginaldalfret requested a review from a team as a code owner October 23, 2026 14:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant