0

I am trying to replace in-between periods and exclamations i.e.,(.,!) with comma. When I tried, my code replaces all the fullstops(.) with comma(,) but, I dont want to change the ending fullstop.

String txt="When I'm bored, I eat. When I'm happy, I eat. When I'm sad, I eat.";

txt = txt.replaceAll("[^\\x00-\\x7f-\\x80-\\xad]", ""); //replaces emojies

//String a=txt.replaceAll("[.!]", ","); //replaces comma or exclamation

System.out.println(txt);

OUTPUT WITH LINE COMMENTED OUT:

When I'm bored, I eat. When I'm happy, I eat. When I'm sad, I eat.

OUTPUT WITH CODE INSTEAD OF COMMENT (and println(a)):

When I'm bored, I eat, When I'm happy, I eat, When I'm sad, I eat,
fedorqui
  • 275,237
  • 103
  • 548
  • 598
bunny sunny
  • 301
  • 6
  • 15

2 Answers2

1

You want to use a negative lookahead:

[\.!](?<!$)

That is: do replace whenever the dot or exclamation mark occur somewhere not at the end of a string.

String a=txt.replaceAll("[\.!](?<!$)", ",");

See the expression and how it matches in: http://www.rubular.com/r/L5oSf1aCa5

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
0

You can just use substring, do the replace and concatanate it back.

String txt="When I'm bored, I eat. When I'm happy, I eat. When I'm sad, I eat.";

String a=txt.substring(0, java.lang.Math.max(txt.lastIndexOf('.'), txt.lastIndexOf('!')));

a=a.replaceAll("[^\x00-\x7f-\x80-\xad]", ""); //replaces emojies

a=a.replaceAll("[.!]", ",")+txt.substring(java.lang.Math.max(txt.lastIndexOf('.'), txt.lastIndexOf('!')),txt.length()); //replaces comma or exclamation

System.out.println(a);