0
 def aString = '[Something-26607] Updating another.txt [Something2] Updating something.txt [Something2] Updating something.txt fsfsfs' 

Is there a way in groovy to get only unique parts between the square brackets and store them in a variable so after I can call them in a for loop. So I will iterate over them

Something-26607 Something2 

I have tried:

def matcher = aString =~ (/\[(?<issue>[^]]+)]/) def result = matcher.find() ? matcher.group('issue') : "" print result 

but I get only get the first match:

Something-26607 
5
  • You can run while (matcher.find()) { and use a pattern like String regex = "\\[(?<issue>[^]]+)](?!.*\\1)"; to find the unique matches in the string, or use your original pattern and use a Set for example. The values are in group 1 of the pattern. Commented Mar 31, 2021 at 10:15
  • Can you give an example. I can't fully understand what you are saying Commented Mar 31, 2021 at 10:25
  • An example of the pattern regex101.com/r/6mqnnR/1 as an example ideone.com/3yeGUi Commented Mar 31, 2021 at 10:30
  • ah I see the java way Commented Mar 31, 2021 at 10:45
  • Would this be better? ideone.com/CZO97s Commented Mar 31, 2021 at 10:46

1 Answer 1

1

I have no experience in Groovy, but reading a little bit about the syntax to get an example, you might use a Set and loop the results using a while loop:

def myList = [] def aString = '[Something-26607] Updating another.txt [Something2] Updating something.txt [Something2] Updating something.txt fsfsfs' def pattern = Pattern.compile("\\[(?<issue>[^]]+)]") def matcher = pattern.matcher(aString) while (matcher.find()) { myList << matcher.group(1) } println myList.toSet() 

Output

[Something2, Something-26607] 

Groovy demo

Without using a Set, you can also use a negative lookahead to check to get the unique values in the string asserting that what is captured in the group does not occur anymore at the right side.

\\[(?<issue>[^]]+)](?!.*\\1) 

Regex demo

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.