Ask Questions?

View Latest Questions

Advertisement


 
 

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) Splits the string, but limits applying regex to only count times.

Example - breaking strings into parts

Input lines often contain many values. An easy way to split a string into separate parts is to use the String split() method. This example splits the line into tokes that are separated by one or more blanks.

// Example of splitting lines from input file with regular expression.
while ((line = input.readLine()) != null) {
    String[] tokens = line.trim().split("\\s+"); // Separated by "whitespace"
    int sum = 0;
    for (String t : tokens) {
        try {
            sum += Integer.parseInt(t);
        } catch (NumberFormatException ex) {
            System.out.println("Not an integer: " + t);
            System.out.println(ex);
        }
    }
    System.out.println("sum = " + sum);
}
Copyleft 2004 Fred Swartz MIT License
Advertisement


DMCA.com