1

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
2
  • contains doesn't use regex. Commented Sep 10, 2015 at 11:02
  • Ahh, thank you. What would you suggest to find regex in String? (fairly new to Java). Commented Sep 10, 2015 at 11:03

2 Answers 2

1

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:

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.