Regex to match a word with at least one letter and any number of digits (no lookaround)

Regexp is built for exactly this, no need for look arounds.

The Regexp

\w*[a-zA-Z]\w*

Explanation:

  • \w: Any letter or number, *: 0 or more times
  • [a-zA-Z]: Any letter, A-Z, caps A-Z or lowercase a-z
  • \w: Any letter or number, *: 0 or more times

Regexper:

Regexper

Online Demo:

regexr.com


completely able to do without lookarounds, just split things into separate entities and explicitly match exactly one letter:

[a-zA-Z0-9]*[a-zA-Z][a-zA-Z0-9]*

Regular expression visualization

Debuggex Demo


If you are using Java, the regex for your requirement is [\\p{L}0-9]*\\p{L}[\\p{L}0-9]*

Explanation:

  1. \p{L} matches any single letter (e.g. A-Za-z, a letter from Greek, German etc. locales)
  2. [\\p{L}0-9]* matches any number of letters or digits because of the quantifier * applied on the character classes consisting of letter and digits.
  3. Thus, the pattern [\\p{L}0-9]*\\p{L}[\\p{L}0-9]* means Any number of letters or digits + A single letter + Any number of letters or digits

Check java.util.regex.Pattern to learn more about these patterns.

Demo:

public class Main {
    public static void main(String[] args) {
        String[] testStrings = { "A1ö1", "_a_", "1Ωω2", "123", "1", "a", "abc", "ABC", "aBc123", "123abc", "123abc123",
                "aBc123aBc", "_123", "123_", "123_123", "1_a", "_", "a_", "a_1.", "123.a", "12.56" };
        for (String s : testStrings) {
            System.out.println(s.matches("[\\p{L}0-9]*\\p{L}[\\p{L}0-9]*") ? s + " matches" : s + " does not match");
        }
    }
}

Output:

A1ö1 matches
_a_ does not match
1Ωω2 matches
123 does not match
1 does not match
a matches
abc matches
ABC matches
aBc123 matches
123abc matches
123abc123 matches
aBc123aBc matches
_123 does not match
123_ does not match
123_123 does not match
1_a does not match
_ does not match
a_ does not match
a_1. does not match
123.a does not match
12.56 does not match

Tags:

Regex