Ask Questions?

View Latest Questions


 
 

String Regex Methods
Posted on: July 26, 2006 at 12:00 AM
In addition the the Pattern and Matcher classes, there is some support for regular expressions in the String class.

Java: String Regex Methods

In addition the the Pattern and Matcher classes, there is some support for regular expressions in the String class.

    boolean b;
    String s, s2, t;
    String  regex;
    String[]  sa;
    
b =  s.matches(regex) True if regex matches the entire string in s. Same as Pattern.matches(regex, s)
s2 =  s.replaceAll(regex, t) Returns a new string by replacing each substring in s that matches regex with t
s2 =  s.replaceFirst(regext) Replaces first substring in s that is matched by regex with String t
sa =  s.split(regex) Breaks s into substrings separated by regex or terminated by the end. There is a problem with this though. If the string is terminated by the separation regex, it will return one extra empty string. If you're separating elements with whitespace ("\\s+"), you can call trim() on the subject first. See the example below.
sa =  s.split(regex, count)