0

I have some code that receives data from an OBD-II adapter and runs it through some regex so that I can identify the part that contains the Trouble Codes. This is it.

dataRecieved = readMessage;
RX.setText(dataRecieved);

if((dataRecieved != null) && dataRecieved.matches("\\s*[A-F0-9]{2} [A-F0-9]{2} [A-F0-9]{2} [A-F0-9]{2} [A-F0-9]{2} [A-F0-9]{2}\\s*\r?\n?")) {
    if(D) Log.i(TAG, "REGEX ");

    dataRecieved = dataRecieved.replace(">", "").trim();
    DTC.setText(dataRecieved);

After the regex I set whatever is received to a TextView in android. However, there's no text set when I run it. I don't know if it's the regex I used. It's supposed to detect something like

>
01 00 14 53 00 00

Including or excluding the prompt.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
v3rse
  • 68
  • 6

1 Answers1

0

The matches() method expects the regex to consume the whole string, so if that > is part of the the message, you need to account for it.

Pattern p = Pattern.compile(">\\s*((?:[A-F0-9]{2}\\s+){5}[A-F0-9]{2})\\s*");
Matcher m = p.matcher(dataRecieved);
if (m.matches())
{
  DTC.setText(m.group(1));
}

By creating a Matcher object instead of using String's matches() method, I was able to use a capturing group to extract the part of the message you're interested in, eliminating the need for the replace() and trim() methods.

Also, \s matches linefeed and carriage-return, so the \r?\n? was redundant.


EDIT: per the comment below, here's a version that matches one or more Trouble Codes on successive lines:

">\\s+((?:(?:[A-F0-9]{2}\\s+){5}[A-F0-9]{2}\\s*)+)"

All the lines are captured in a single block. This also captures the newline at the end of the last line if there is one, so you may need to trim that off.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • Thanks a lot, seems to be working now.Just wanted know though what does the ?: used in the second grouping mean? – v3rse May 12 '13 at 06:30
  • `(?:...)` is a non-capturing group. There's a pretty good explanation of groups **[here](http://www.regular-expressions.info/brackets.html)**. – Alan Moore May 12 '13 at 06:59
  • Thanks. I also want to know if it will work for multiple lines of codes. For example `01 00 14 53 00 00 03 01 90 88 70 10 03 00 00 00 00 00 ` In this case the pattern is repeated 3 times. – v3rse May 16 '13 at 12:57
  • I'm assuming that's supposed to be three Trouble Codes, each on its own line. I've added the new regex to my answer. – Alan Moore May 16 '13 at 18:37