Wednesday, May 4, 2011

Using Regular Expressions with String.matches()

s,matches("regex") evaluates true if the WHOLE string can be matched with string s.

Now the regex will be containing character classes, to define some pattern to be searched. These character classes are defined over here. Now with the help of this we can see some simple regular expression handling in java.
So to match bad or Bad we can use regex as “[Bb]ad”
str.mathces("[Bb]ad");

To match alternatives for a whole string, we use pipe:

str.mathces("bad|ugly");

Using ranges

To match hexadecimal digit:

[0-9A-F]

To match hexadecimal digit with case insensitive way:
[0-9A-Fa-fA-F]

Seeing the whole examples:

public class StringMatcher{
// Returns true if the string matches exactly "true"
public static boolean isTrue(String s){
return s.matches("true");
}
// Returns true if the string matches exactly "true" or "True"
public static boolean isTrueVersion2(String s){
return s.matches("[tT]rue");
}

// Returns true if the string matches exactly "true" or "True"
// or "yes" or "Yes"
public static boolean isTrueOrYes(String s){
return s.matches("[tT]rue|[yY]es");
}

// Returns true if the string contains exactly "true"
public static boolean containsTrue(String s){
return s.matches(".*true.*");
}


// Returns true if the string contains of three letters
public static boolean isThreeLetters(String s){
return s.matches("[a-zA-Z]{3}");
// Simpler from for
//        return s.matches("[a-Z][a-Z][a-Z]");
}



// Returns true if the string does not have a number at the beginning
public boolean isNoNumberAtBeginning(String s){
return s.matches("^[^\\d].*");
}
// Returns true if the string contains a arbitrary number of characters except b
public static boolean isIntersection(String s){
return s.matches("([\\w&&[^b]])*");
}
// Returns true if the string contains a number less then 300
public static boolean isLessThenThreeHundret(String s){
return s.matches("[^0-9]*[12]?[0-9]{1,2}[^0-9]*");
}

}

No comments:

Post a Comment

Chitika