I don’t understand why with this regex the method returns false;
Pattern.matches("\\bi", "an is");
the character i is at a word boundary!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Java,
matchesattempts to match a pattern against the entire string.This is true for
String.matches,Pattern.matchesandMatcher.matches.If you want to check if there’s a match somewhere in a string, you can use
.*\bi.*. In this case, as a Java string literal, it’s".*\\bi.*".java.util.regex.MatcherAPI linksboolean matches(): Attempts to match the entire region against the pattern.What
.*meansAs used here, the dot
.is a regex metacharacter that means (almost) any character.*is a regex metacharacter that means “zero-or-more repetition of”. So for example something likeA.*BmatchesA, followed by zero-or-more of “any” character, followed byB(see on rubular.com).References
Related questions
.*?and.*for regexNote that both the
.and*(as well as other metacharacters) may lose their special meaning depending on where they appear.[.*]is a character class that matches either a literal period.or a literal asterisk*. Preceded by a backslash also escapes metacharacters, soa\.bmatches"a.b".Related problems
Java does not have regex-based
endsWith,startsWith, andcontains. You can still usematchesto accomplish the same things as follows:matches(".*pattern.*")– does it contain a match of the pattern anywhere?matches("pattern.*")– does it start with a match of the pattern?matches(".*pattern")– does it end with a match of the pattern?StringAPI quick cheat sheetHere’s a quick cheat sheet that lists which methods are regex-based and which aren’t:
String replace(char oldChar, char newChar)String replace(CharSequence target, CharSequence replacement)boolean startsWith(String prefix)boolean endsWith(String suffix)boolean contains(CharSequence s)String replaceAll(String regex, String replacement)String replaceFirst(String regex, String replacement)String[] split(String regex)boolean matches(String regex)