Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regular expression with hyphen

Tags:

java

regex

I need to match and parse data in a file that looks like:

4801-1-21-652-1-282098
4801-1-21-652-2-282098
4801-1-21-652-3-282098
4801-1-21-652-4-282098
4801-1-21-652-5-282098

but the pattern I wrote below does not seem to work. Can someone help me understand why?

final String patternStr = "(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)";
final Pattern p = Pattern.compile(patternStr);

while ((this.currentLine = this.reader.readLine()) != null) {
    final Matcher m = p.matcher(this.currentLine);
    if (m.matches()) {
        System.out.println("SUCCESS");
    }
}
like image 623
Amir Afghani Avatar asked Dec 17 '10 23:12

Amir Afghani


2 Answers

It looks correct. Something odd is conatined in your lines, probably. Look for some extra spaces and line breaks.

Try this:

final Matcher m = p.matcher(this.currentLine.trim());
like image 176
Roman Avatar answered Sep 30 '22 20:09

Roman


Have you tried escaping the - as \\-?

like image 31
Jason S Avatar answered Sep 30 '22 21:09

Jason S