Kyle Weller
Kyle Weller

Reputation: 2623

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?

Upvotes: 5

Views: 5922

Answers (2)

tim_yates
tim_yates

Reputation: 171144

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

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

Upvotes: 7

Reimeus
Reimeus

Reputation: 159844

For Groovy, you will need to find all matches from your String. Replace:

matcher.find { newByte ->

with

matcher.findAll { newByte ->

Upvotes: 3

Related Questions