Skip to Content RSS Feed
I Build Search
Self Picture

Natural Language Processing, Data Mining, Information Extraction and Search consultant.

 LEARN MORE   GET IN TOUCH 

Apr 16 2009

Java Regex Matching

Took me half a day to figure out matcher.find() had to be called first. Gaah!

RegexTest.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Tester {
    public static void main(String args[]) 
    {
        Pattern pattern = Pattern.compile("name=\"QTime\">(\\d+)</int>");
        Matcher matcher = pattern.matcher("<response><lst name=\"responseHeader\">" + 
            "<int name=\"status\">0</int><int name=\"QTime\">2</int></lst></response>");
        
        try {
            if(matcher.find()) {
                System.out.println(matcher.group(1));
            }
        }
        catch (Exception e) {
            System.out.println("Couldn't find QTime");
        }
    }
}

P.S. I love Python