简体   繁体   中英

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

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.

you forgot to add the digits in your regex, you are just checking for one or more instances of the questionmark. This should do what you are trying to achive.

String a = "12?34567";
System.out.println(a.replaceAll("\\?\\d*$", ""));

If you just want to remove them after the first questionmark as stated in your comment you could simply do

String a = "12??1?1231";
System.out.println(a.replaceAll("\\?.*", ""));
    String a = "12?34567";
    String[] split = a.split("\\?");
    System.out.println(split[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM