Gniewny Gienek
Gniewny Gienek

Reputation: 23

Validate each line using a single regex

I am writing an application in Java that is supposed to communicate to an external device. The device responds using the following format

01 02 05 0A 2D 3E
01 02 12 2B 09 07

As a response I may get at least one line, but often there are several.

I tried to validate the response using a simple regular expression

([0-9a-fA-F]{2} ?){6}\r

But it returns true if at least one line is correct, and I need to validate all lines. I know that I may split the response into separate lines and validate each in a loop, but the question is - is it possible to validate all lines using a single regex?

Update (the Java code I am using):

Pattern pattern = Pattern.compile("([0-9a-fA-F]{2} ?){6}\r");
String string = "01 02 05 qA 2D 3E\r01 02 12 2B 09 07\r"; // qA - 4th number is invalid

Matcher matcher = pattern.matcher(string);

if (matcher.find()) {
   System.out.println(matcher.group());
}

Upvotes: 2

Views: 755

Answers (1)

Pshemo
Pshemo

Reputation: 124245

it returns true if at least one line is correct

It is because find method is trying to find substring in your input which can be matched by your regex. If you want to check if entire input is matched my regex use matches().

Also, your regex

([0-9a-fA-F]{2} ?){6}\r

can only match one line which ends with \r. To let regex accept more lines simply put it in parenthesis and add + after it

(([0-9a-fA-F]{2} ?){6}\r\n?)+

I added optional \n after \r in case line separators could be \r\n. You can also use (\r\n?|$) in case last line will not contain line separators

Last thing is that as you already know your code example contains q instead of 0 which prevents regex from matching.

So try this way

Pattern pattern = Pattern.compile("(?:([0-9a-fA-F]{2} ?){6}\r)+");
String string = "01 02 05 0A 2D 3E\r01 02 12 2B 09 07\r"; 

Matcher matcher = pattern.matcher(string);

if (matcher.matches()) {
    System.out.println(matcher.group());
}

Upvotes: 1

Related Questions