0

I have the below groovy code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String myInput="License_All (12313)"
String myRegex="\\(\\d+\\)"


String ResultString
Pattern regex
Matcher regexMatcher

regex = Pattern.compile(myRegex, Pattern.DOTALL);

regexMatcher = regex.matcher(myInput);

List<String> matchList = new ArrayList<String>();
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}

for(int i=0;i<matchList.size();i++)
{
myInput=myInput.replaceAll( matchList[i], '')
println matchList[i]
}
println myInput

It is supposed to remove (12313) part but instead it gives me the below output

(12313)
License_All ()

How do i remove all the bracket portion (12313)?

2 Answers 2

2

The matchList will contain the matched part, i.e. (12313). This one is then again taken as regular expression within replaceAll and therefore interpreted as group. Thus the brackets are not removed.

Instead you can use your regex directly in replaceAll:

myInput.replaceAll(myRegex, "")
Sign up to request clarification or add additional context in comments.

Comments

1

Becaue you are using replaceAll, it is expecting a Pattern as the first element

myInput = myInput.replaceAll( Pattern.compile(myRegex, Pattern.DOTALL), '' )

Should do it...


As an aside, your original code can be made into more idiomatic Groovy (rather than basically Java) like so -- obviously, this has the same issue as in your original question, it's just a more Groovy way of writing code:

import java.util.regex.Pattern

String myInput = "License_All (12313)"

def regex = Pattern.compile( /\(\d+\)/, Pattern.DOTALL);

List<String> matchList = ( myInput =~ regex ) as List

matchList.each { m ->
  myInput = myInput.replaceAll( m, '')
  println m
}
println myInput

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.