String s = "111\\1111\\"; s = s.replace("\\", "/"); System.out.println(s); 111/1111/
/** * Replaces each substring of this string that matches the literal target * sequence with the specified literal replacement sequence. The * replacement proceeds from the beginning of the string to the end, for * example, replacing "aa" with "b" in the string "aaa" will result in * "ba" rather than "ab". * * @param target The sequence of char values to be replaced * @param replacement The replacement sequence of char values * @return The resulting string * @throws NullPointerException if <code>target</code> or * <code>replacement</code> is <code>null</code>. * @since 1.5 */ public String replace(CharSequence target, CharSequence replacement) { return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( this).replaceAll(Matcher.quoteReplacement(replacement.toString())); }
这样可以
为什么要用正则表达式
这样不行,替换不过来的!!!!!!!!!!
= =。。你自己去看 源码吧。。他的参数是String 类型的。。如果是char类型才不是在用正则
str.replace("\\", "/")!!!
只能转成字符数组形式,再取每一个值进行改变了,
a=a.replaceAll("\\\\", "/");
System.out.println("abcdef\\".replace("\\","/"));
s = s.replace("\\", "/");
System.out.println(s);
111/1111/
* Replaces each substring of this string that matches the literal target
* sequence with the specified literal replacement sequence. The
* replacement proceeds from the beginning of the string to the end, for
* example, replacing "aa" with "b" in the string "aaa" will result in
* "ba" rather than "ab".
*
* @param target The sequence of char values to be replaced
* @param replacement The replacement sequence of char values
* @return The resulting string
* @throws NullPointerException if <code>target</code> or
* <code>replacement</code> is <code>null</code>.
* @since 1.5
*/
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
String str = "a" 可以匹配单个"a",相当于[a]{1}
String str = "a*" 可以匹配多个"a",相当于[a]{1,n}
当String str = "a*" 匹配多个"a*" 时,这还算一个正则表达式?我上面说的,replace用的不是正则,我指它的参数不是一个正则表达式,楼上的代码中
Pattern.compile(target.toString(), Pattern.LITERAL)
这个参数相信你也注意到了,我就不贴上来了。
不是一个正则表达式你认为是什么?
Pattern.LITERAL 是什么意思?设置之后难道就不是一个正则表达式了?那我到得听一下大侠的高见了。
好比:String str = "a\*";难道这不是一个表达式吗?
System.out.println(a);// aa/
String b = "aa\\".replaceAll("\\\\", "/");
System.out.println(b);// aa/