Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy/Java regex looping through matches on pattern

Tags:

java

regex

groovy

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?

like image 438
Kyle Weller Avatar asked Dec 27 '22 11:12

Kyle Weller


2 Answers

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

String stream = str.findAll( /\b[A-F0-9]{2}\b/ ).join()
like image 130
tim_yates Avatar answered Jan 02 '23 03:01

tim_yates


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

matcher.find { newByte ->

with

matcher.findAll { newByte ->
like image 34
Reimeus Avatar answered Jan 02 '23 01:01

Reimeus