0

I have some expected pattern for data that I receive in my server. The following 2 lines are expected as I wish.

¬14AAAA3170008@¶

%AAAA3170010082¶

So, to check if the data it's fine, I wrote the following regex:

(?<pacote>\\A¬\\d{2}[a-fA-F0-9]{4}\\d{7}.{2})
(?<pacote>\\A[$%][a-fA-F0-9]{4}\\d{10}.)

And it works fine in regex101.com but Java Pattern and Matcher doesn't understand this regex as expected. Here goes my Java code

String data= "¬14AAAA3170008@¶%AAAA3170010082¶";
Pattern patternData = Pattern.compile( "(?<pacote>\\A¬\\d{2}[a-fA-F0-9]{4}\\d{7}.{2})", Pattern.UNICODE_CASE  );
Matcher matcherData = patternData.matcher( data );


if( matcherData .matches() ){
  System.out.println( "KNOW. DATA[" + matcherData .group( "pacote" ) + "]");

}else{
  System.out.println( "UNKNOW" );

}

And it didn't worked as expected. Could someone help me figure what mistake I'm doing?

1
  • "And it didn't worked as expected." In what way? Did it not match? Did it match but with the wrong groups? Commented Aug 27, 2015 at 15:59

1 Answer 1

1

You're using Matcher#matches, which matches the whole input.

However, the Pattern you're using only applies for the first input, and your whole input contains the two cases concatenated.

On top of that, the \\A boundary matcher implies the pattern follows the start of the input.

You can use the following pattern to generalize and match the two:

String test = "¬14AAAA3170008@¶%AAAA3170010082¶";
Pattern p = Pattern.compile(
//   | named group definition
//   |         | actual pattern
//   |         | | ¬ + 2 digits or $%
//   |         | |            | 4 hex alnums
//   |         | |            |              | 7 to 10 digits
//   |         | |            |              |        | any 1 or 2 characters    
//   |         | |            |              |        |      | multiple times (2 here)
    "(?<pacote>((¬\\d{2}|[$%])[a-fA-F0-9]{4}\\d{7,10}.{1,2})+)"
);
Matcher m = p.matcher(test);
if (m.find()) {
    System.out.println(m.group("pacote"));
}

Output

¬14AAAA3170008@¶%AAAA3170010082¶
Sign up to request clarification or add additional context in comments.

1 Comment

@mbomb007 looks like you're right, will amend the comment, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.