I am quite bad at Java Regular expression so I hope you guys will help me.
String variable = "My life is better ";
String variable2 = "My life01 is better";
Now I have to write a code which would return true if the string has only “life”
So I should get TRUE only for variable not for variable2 because it has life but “01” too.
~thanks.
I have tried
if (variable.contains("life")){
System.out.println("TRUE");}
It return TRUE for both.
See solution :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Pattern p = Pattern.compile("\\blife\\b");
Matcher m = p.matcher("life0 is better");
boolean b = m.find();
System.out.println(b);
}
}
Use the following regex: –
with
PatternandMatcherclass. This will match for complete word. (\bdenote word boundary)You would have to use
Matcher#findmethod, to check whether a string contains this pattern.Note: – If you want to use
String.matches, which would be appropriate here, than going withPatternandMatcher, you would have to add.*in the front and theend. Because,String.matchesmatches the whole string.For e.g: –
In the second Regex,
.*matches the string before and afterlife.