Question

I am trying to pass a sentence to a function and have multiple occurrences of a pattern removed before returning.

My function looks like this....

  public String removeExtraStars(String str){
    String b = str.replaceAll("\\*\\s{2,}", "* ");
    return b;
  }

An example input is "hi my name is * *" I am trying to get the output to look like "hi my name is *" But it just wont do it. I have tried it on string like "my dinner was * * nice" hoping it would output "my dinner was * nice" But nothing worked. Can someone please tell me what i am doing wrong. thanks

p.s. I think the most complicated output would look like this "* and * and * and *"

Was it helpful?

Solution

You will want to change your regex to search for not only a * but for whitespace and additional *'s afterwards.

String str = "hi my name is * * * and * is * *";
String b = str.replaceAll("\\*(\\s+\\*)+", "*");

output:

hi my name is *  and * is * 

OTHER TIPS

Your regular expression replaces * (asterisk followed by two spaces) but not * *. If I read your request correctly, you need to group before the quantifier: (\\*\\s){2,} which says "astrisk followed by space, at least two times".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top