Reputation: 333
Dont know how to ask more correctly, so will try as I can.
There is one example string where we are searching and another pattern String:
I need some way to figure out if example contains pattern (it comes to my mind something like example.indexOf(pattern) > - 1)
Pattern = "b*b"
Example = "gjsdng" - false;
Example = "bob" - true;
Example = "bab" - true;
Example = "gdfgbUbfg" - true;
Upvotes: 0
Views: 104
Reputation: 8105
Brrrrr.
There is absolutely no need to create the Pattern
multiple times. Just compile it once:
Pattern pattern = Pattern.compile( "b.b" );
Furthermore there is no need to match the whole String. Just to find one occurrence of the searched String. So this is what you're looking for:
assertFalse( pattern.matcher( "Gollum" ).find() );
assertTrue( pattern.matcher( "bob" ).find() );
assertTrue( pattern.matcher( "babe" ).find() );
assertTrue( pattern.matcher( "Alibaba" ).find() );
Upvotes: 0
Reputation: 46841
You can use String#matches(regex) method with .*?b.b.*
regex pattern to match the text.
System.out.println("gjsdng".matches(".*?b.b.*")); //false
System.out.println("bob".matches(".*?b.b.*")); //true
System.out.println("bab".matches(".*?b.b.*")); //true
System.out.println("gdfgbUbfg".matches(".*?b.b.*")); // true
Pattern explanation:
.*? any character except \n (0 or more times
(matching the least amount possible))
b 'b'
. any character except \n
b 'b'
.* any character except \n (0 or more times
(matching the most amount possible))
Upvotes: 5
Reputation: 1293
.*b[A-Za-z]b.*
is the regex pattern you are looking for.
b
letter b
in character 1 of pattern[A-Za-z]
any letter A-Z or a-z in character 2 of patternb
letter b
in character 3 of pattern
System.out.println("bobby".matches(".*b[A-Za-z]b.*")); // true
System.out.println("gjsdng".matches(".*b[A-Za-z]b.*")); // false
System.out.println("bob".matches(".*b[A-Za-z]b.*")); // true
System.out.println("bab".matches(".*b[A-Za-z]b.*")); // true
System.out.println("gdfgbUbfg".matches(".*b[A-Za-z]b.*")); // true
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Upvotes: 0