如何回复Java字符串中的最后一个空格?
我试着做这样的事情:如何回复Java字符串中的最后一个空格?,java,regex,string,Java,Regex,String,我试着做这样的事情: String result = "Most Trees Are Blue "; //Should be return a string without last space return result.replaseAll("REGEX", ""); 结果必须是大多数树都是蓝色的,我可以做到: return new StringBuilder(result).deleteCharAt(result.length()-1).toString(); 但我想用正则表达式
String result = "Most Trees Are Blue ";
//Should be return a string without last space
return result.replaseAll("REGEX", "");
结果必须是大多数树都是蓝色的,我可以做到:
return new StringBuilder(result).deleteCharAt(result.length()-1).toString();
但我想用正则表达式
我怎么做?
对于正则表达式,可以使用replaceAll\\s+$,如 该\\s+将匹配一个或多个空白字符,字符串末尾的$表示,然后是替换值。产出是,
'Most Trees Are Blue'
您也可以使用like
对于正则表达式,可以使用replaceAll\\s+$,如 该\\s+将匹配一个或多个空白字符,字符串末尾的$表示,然后是替换值。产出是,
'Most Trees Are Blue'
您也可以使用like
如您所述,使用正则表达式的方法是
String result = "Most Trees Are Blue ".replaceAll("\\s+$", "");
System.out.println(result); //=> "Most Trees Are Blue"
如您所述,使用正则表达式的方法是
String result = "Most Trees Are Blue ".replaceAll("\\s+$", "");
System.out.println(result); //=> "Most Trees Are Blue"
@SotiriosDelimanolis我想它也会删除前导空格。@AvinashRaj为true时,OP的示例不包括前导空格。@SotiriosDelimanolis我想它也会删除前导空格。@AvinashRaj为true时,OP的示例不包括前导空格。