Felix Schäfer
Felix Schäfer

Reputation: 37

Java Regular Expression remove Matches from String

I'm trying to figure out how to remove the found matches from my String. So my Code sample currently looks like this:

public void checkText() {
    String helper = "985, 913, 123, SomeotherText, MoreText, MoreText";
    Pattern pattern = Pattern.compile("\\b\\d{3}");
    Matcher matcher = pattern.matcher(helper);
    while (matcher.find()) {
        String newtext = "Number: " + matcher.group() + "\n"+ newtext;
        helper.replaceAll(matcher.group(),"");
    }
    newtext = newtext + "________________\n"+ helper;
    editText.setText(newtext);
}

So my input string is: 985, 913, 123, SomeotherText, MoreText, MoreText

After running the code what I would like to see is this:

Number: 985
Number: 913
Number: 123
________________________
SomeotherText, MoreText, MoreText

Anyone can tell me whats wrong in my current code?

Upvotes: 1

Views: 663

Answers (2)

Eritrean
Eritrean

Reputation: 16498

Since you are already using the Matcher class you can also use the method Matcher.appendReplacement for the replacement:

public void checkText() {
    String helper = "985, 913, 123, SomeotherText, MoreText, MoreText";
    Pattern pattern = Pattern.compile("\\b\\d{3}, ");
    Matcher matcher = pattern.matcher(helper);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        System.out.println("Number:"+matcher.group());
        matcher.appendReplacement(sb, "");
    }
    matcher.appendTail(sb);
    System.out.println(sb.toString());
}

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163207

There are a few things you could update in the code:

  • You should set the return of the replacement to helper
  • If you only replace with an empty string, your string will start with , , , in the replacement leaving the comma's and the follwing space
  • You might initialize the variable String newtext = "";

See a Java demo

Your code might look like:

String helper = "985, 913, 123, SomeotherText, MoreText, MoreText";
Pattern pattern = Pattern.compile("\\b\\d{3}");
Matcher matcher = pattern.matcher(helper);
String newtext = "";

while (matcher.find()) {
    newtext = "Number: " + matcher.group() + "\n"+ newtext;
    helper = helper.replaceAll(matcher.group() + ", ","");
}
newtext = newtext + "________________\n"+ helper;
System.out.println(newtext);

Result:

Number: 123
Number: 913
Number: 985
________________
SomeotherText, MoreText, MoreText

Upvotes: 2

Related Questions