1

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?

2
  • 3
    What output do you get? Commented Jul 11, 2019 at 12:22
  • 1
    You're replacing only numbers and expect commas to be replaced as well. You should add them to your regex as well. Commented Jul 11, 2019 at 12:31

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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());
}

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.