Amir Afghani
Amir Afghani

Reputation: 38521

Java regular expression with hyphen

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");
    }
}

Upvotes: 5

Views: 21104

Answers (4)

Amir Afghani
Amir Afghani

Reputation: 38521

There is white space in the data

 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

final String patternStr = "\\s*(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)";

Upvotes: 1

fastcodejava
fastcodejava

Reputation: 41087

It should work. Make sure there is no invisible characters, you an trim each line. You can refine the code as :

final String patternStr = "(\\d{4})-(\\d{1})-(\\d{2})-(\\d{3})-(\\d{1})-(\\d{6})";

Upvotes: 3

Roman
Roman

Reputation: 66156

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());

Upvotes: 7

Jason S
Jason S

Reputation: 189626

Have you tried escaping the - as \\-?

Upvotes: 5

Related Questions