MathAng
MathAng

Reputation: 452

Matcher java doesn't work but regex seems to be good

I want to find instance of regex in my string. But it doesn't work. My regex seems to be good.

My string is like that :

LB,32736,0,T,NRJ.POMPES_BACHE.PUISSANCE_ELEC_INST,20190811T080000.000Z,20190811T194400.000Z
TR,NRJ.POMPES_BACHE.PUISSANCE_ELEC_INST,0,65535,1,1,,0,0,2
20190811T080000.000Z,0.00800000037997961,192
20190811T080100.000Z,0.008999999612569809,192
20190811T080200.000Z,0.008999999612569809,192
LB,32734,0,T,NRJ.POMPES_BACHE.PUISSANCE_ELEC_CPT,20190811T080000.000Z,20190811T201200.000Z
TR,NRJ.POMPES_BACHE.PUISSANCE_ELEC_CPT,0,65535,1,1,,0,0,2
20190811T080000.000Z,0.6743068099021912,192
20190811T080100.000Z,0.6744459867477417,192
20190811T080200.000Z,0.6745882630348206,192
20190811T080300.000Z,0.6747232675552368,192
20190811T080400.000Z,0.6748600006103516,192
20190811T080500.000Z,0.6749916672706604,192
20190811T080600.000Z,0.6751362681388855,192

And I want to match only lines which have this format

20190811T080000.000Z,0.00800000037997961,192

So I have tried this regex

^([^,]*,){2}[^,]*$

And work on this website : https://regex101.com/r/iIbpgB/3

But, when I implement it on Java, it doesn't work.

Pattern pattern = Pattern.compile("^([^,]*,){2}[^,]*$");
                Matcher matcher = pattern.matcher(content);
                if ( matcher.find()){
                    System.out.println(matcher.group());
                }

You can verify here : https://www.codiva.io/p/e83bcde1-8528-4330-94a2-58fe80afffc0

Someone have an explain?.. Thanks

Upvotes: 1

Views: 64

Answers (2)

LMG-UK
LMG-UK

Reputation: 11

You changed between if and while, do you want 1 match or all of them?

Pattern pattern = Pattern.compile("^([^,]*,){2}[^,]*$");
Matcher matcher = pattern.matcher(content);
while ( matcher.find()){
    System.out.println(matcher.group());
}

This version will keep looping while the matcher continues to match the regex in the content string.

Upvotes: 1

anubhava
anubhava

Reputation: 784998

Your are missing MULTILINE mode in your Java regex, you may use:

Pattern pattern = Pattern.compile("^([^,]*,){2}[^,]*$", Pattern.MULTILINE);

or else use inline:

Pattern pattern = Pattern.compile("(?m)^([^,]*,){2}[^,]*$");

Upvotes: 2

Related Questions