Josh
Josh

Reputation: 13

Regex check if string first characters are digits

Trying to use Regex to detect is a String starts with 2 characters followed by an optional space, followed by an optional letter.

This is my attempt: but does not seem to catch my test data

!string.matches("\\b\\d{2}\\s?[a-Z]?")

Test Data:

23: sentence here

Upvotes: 1

Views: 4160

Answers (2)

Pshemo
Pshemo

Reputation: 124225

contains doesn't use regex. You may want to create Pattern and then for each of your string separate Matcher and check if it can find regex you described. So your code can look like

private static final Pattern p = Pattern.compile("^\\d\\d\\s?[a-Z]?");
public static boolean test(String str){
    return p.matcher(str).find();
}

(you can rename this method into something more descriptive)


You could try with yourString.matches(regex) but this method checks if regex matches entire string, not just part of it, which means that it can be inefficient if your string is long, and you want to check only first few characters.

Upvotes: 0

slartidan
slartidan

Reputation: 21576

Use matches instead of contains:

!string.matches("^\\d{2}\\s?[a-Z]?.*")

The regular expression works like this:

  • ^ searches the beginning of the string
  • \\d{2}\\s?[a-Z]? was your search pattern
  • .* allows the rest of the string to be anything

Have a look at the API:

Upvotes: 1

Related Questions