public static void main (String[] args) {
String a = "\\joe\\jill\\";
String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");
System.out.println(b);
}
$用于删除字符串末尾的序列。^用于在开始时移除。
作为替代方法,您可以使用以下语法:
String b = a.replaceAll("\\\\$|^\\\\", "");
|的意思是“或者”。
如果您想修剪其他字符,只需调整 regex:
String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining
/** Trim all occurrences of the string <code>rmvval</code> from the left and right of <code>src</code>. Note that <code>rmvval</code> constitutes an entire string which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String rmvval) {
return trim(src,rmvval,rmvval,true);
}
/** Trim all occurrences of the string <code>lftval</code> from the left and <code>rgtval</code> from the right of <code>src</code>. Note that the values to remove constitute strings which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String lftval, String rgtval, boolean igncas) {
int str=0,end=src.length();
if(lftval.length()==1) { // optimize for common use - trimming a single character from left
char chr=lftval.charAt(0);
while(str<end && src.charAt(str)==chr) { str++; }
}
else if(lftval.length()>1) { // handle repeated removal of a specific character sequence from left
int vallen=lftval.length(),newstr;
while((newstr=(str+vallen))<=end && src.regionMatches(igncas,str,lftval,0,vallen)) { str=newstr; }
}
if(rgtval.length()==1) { // optimize for common use - trimming a single character from right
char chr=rgtval.charAt(0);
while(str<end && src.charAt(end-1)==chr) { end--; }
}
else if(rgtval.length()>1) { // handle repeated removal of a specific character sequence from right
int vallen=rgtval.length(),newend;
while(str<=(newend=(end-vallen)) && src.regionMatches(igncas,newend,rgtval,0,vallen)) { end=newend; }
}
if(str!=0 || end!=src.length()) {
if(str<end) { src=src.substring(str,end); } // str is inclusive, end is exclusive
else { src=""; }
}
return src;
}