Search code examples
javaregexstringreplaceall

How do I remove trailing characters after Question mark(?) in a String?


I need to remove the trailing characters after 2 from the below String

String a = "12?34567";

My expected String output should be 12

I tried the below replaceAll method. But It did not work.

a.replaceAll("\\?+$", ""));

Please help


Solution

  • Instead of using a regex, use indexOf:

    final int index = orig.indexOf('?');
    return index == -1 ? orig : orig.subString(0, index);
    

    If you want to leave the question mark as is, just add 1 to index in the substring operation above.