This content has been marked as final. Show 6 replies
968970 wrote:I wouldn't be so sure about it. It might be shorter, but not necessary cleaner.
i think using replaceAll will be much cleaner.
You can easily create a pattern that matches to anychar-asterisk-anychar, with a bit of additional trickery for start of string and end of string.
What have you tried so far? I won't give you the answer right away, because you need to make an effort yourself if you want to use regular expressions :)
968970 wrote:See, you're getting there. You already have one case dealt with. You could use the or operator to match the rest of the cases.
And if i am using the regex below
String str = "abc*def*";
String str1 = str.replaceAll(".[*].", "");
Then I am getting the string result as abef* but i want abe.
If we take the general case, where asterisk is surrounded by a character on both sides, we get ".\\*." or what you have, except you're using character classes a bit unnecessarily there.
Now we want the case handled when the String ends with an asterisk, so we add ".\\*" to the pattern.
That gives us ".\\*.|.\\*", so the pattern matches even if the other side doesn't have a character.
Now you can add one more case for when the string starts with an asterisk.
As you can see, it's not exactly a clear solution and in most cases a loop would be a lot easier to understand.