3

Hi I have to match a pattern like below

{digit 0-1 or A}:{digit 0-1 or A}:{digit 0-1 or A}|{digit 0-1 or A}:{digit 0-1 or A}:{digit 0-1 or A}|{digit 0-1 or A}:{digit 0-1 or A}:{digit 0-1 or A}

I am using the following code -

String accMatrixPattern = "\\d{1,1}|[A]:\\d{1,1}|[A]:\\d{1,1}|[A]|[A]:\\d{1,1}|[A]"; 
String accMatrx = "1:A:1|0:1:1|0:1:1";

If I am using only "\\d{1,1}|[A]"; it is working but not combined.

Please suggest How to match Regular Expression

Thanks

4 Answers 4

7

If you're trying to match just 0, 1 or A in each position, you can use:

String accMatrixPattern = "[01A]:[01A]:[01A]\\|[01A]:[01A]:[01A]\\|[01A]:[01A]:[01A]";

If you want to take values, -1, 0, 1, A:

String accMatrixPattern = "([01A]|-1):([01A]|-1):([01A]|-1)\\|([01A]|-1):([01A]|-1):([01A]|-1)\\|([01A]|-1):([01A]|-1):([01A]|-1)";
Sign up to request clarification or add additional context in comments.

2 Comments

Thank u very much. It is working. I will accept the answer after 9 minutes :)
@ BTW if I want to take -1 to 1 range then how to do it??
2
String regex = "[01A]:[01A]:[01A](\\|[01A]:[01A]:[01A]){2}";

This matches one character (either a 0 or a 1 or the letter A), followed by a colon, followed by another character like the first, followed by a colon, followed by a third character like the first.

Then it takes a | character (note that it's escaped), followed by the same thing again but twice.

Comments

2

The problem is that the | on the whole string, so, with brackets added to indicate how grouping will happen, your regex would look something like this:

"(\\d{1,1})|([A]:\\d{1,1})|([A]:\\d{1,1})|([A])|([A]:\\d{1,1})|([A])"

So it would match a string consisting of only 1 or A:0 or A:1 or ...

So you should add some brackets to make it process it correctly.

The {1,1} is redundant, you can just use \\d.

A doesn't have to be inside [].

You need to escape the | if you're talking about the literal character.

"(\\d|A):(\\d|A):(\\d|A)\|(\\d|A):(\\d|A):(\\d|A)\|(\\d|A):(\\d|A):(\\d|A)"

You can now use some {} to cancel out the redundancy.

"(\\d|A):(\\d|A)(:(\\d|A)\|(\\d|A):(\\d|A)){2}"

For only digits 0-1, using [01A] (as suggested in the other answers) is probably better.

"[01A]:[01A](:[01A]\|[01A]:[01A]){2}"

1 Comment

Yes I was getting that but did not be able to put bracket; Thanks for your explanation.
0
[01A]:[01A]:[01A](?:\\|[01A]:[01A]:[01A]){2}

?: to specify this is a non capturing group

Comments

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.