Reputation: 39
Using java how can I replace a character in a string ONLY when it occurs single?
ex:
Replace single *
with a #
input string:
a*b**c*d***e
output string:
a#b**c#d***e
inputString.replaceAll("*", "#");
replaces all the *s
and returns a#b##c#d###e
Upvotes: 2
Views: 137
Reputation: 81054
You can use negative lookahead and lookbehind:
String s = "a*b**c*d***e";
String r = s.replaceAll("(?<!\\*)\\*(?!\\*)", "#"); // a#b**c#d***e
This reads: "an * not preceeded by an * and not followed by an *" (note the fact that *
must be escaped in a regular expression, as it is a meta character).
Upvotes: 5
Reputation: 2973
Try using the charAt(n) method, setting the number n (the parameter) as the number of the * single ones, and then set the string to the "#" and see if that helps.
Upvotes: -1