javaregexgroovy

Groovy/Java regex looping through matches on pattern


I have a string that holds some bytes represented in hex that I want to extract. For example:

String str = "051CF900: 00 D3 0B 60 01 A7 16 C1  09 9C"

I want to extract the values and concatenate them together in a string so that it looks like:

00D30B6001A716C1099C

My attempt:

String stream = "";
Pattern pattern = Pattern.compile("\\b[A-F0-9]{2}\\b");
matcher = pattern.matcher(str);
matcher.find{ newByte ->
  println(newByte);
  stream += newByte;
};
println(stream);

When I try to add each byte to the stream it seems to stop looping. If I remove that line each byte is printed out successfully. Why would the loop break when I add newByte to stream?


Solution

  • As this is Groovy, you can change all of your code to:

    String stream = str.findAll( /\b[A-F0-9]{2}\b/ ).join()