当前位置: 技术问答>java相关
简单的问T,字符串替换!快来抢分!
来源: 互联网 发布时间:2017-04-18
本文导语: 我想将字符串中的括号删除掉 但 str.replaceAll("(",""); 或 str.replaceAll("("," "); 会报错如下: java.util.regex.PatternSyntaxException: Unclosed group near index 1 | 这个是正则表达式的用法,如下: //jdk1.4以上 import jav...
我想将字符串中的括号删除掉
但
str.replaceAll("(","");
或
str.replaceAll("("," ");
会报错如下:
java.util.regex.PatternSyntaxException: Unclosed group near index 1
但
str.replaceAll("(","");
或
str.replaceAll("("," ");
会报错如下:
java.util.regex.PatternSyntaxException: Unclosed group near index 1
|
这个是正则表达式的用法,如下:
//jdk1.4以上
import java.uti.regex.*;
String str="123(456(789";
String str1="\(";
java.util.regex.Pattern p=Pattern.compile(str1);
Matcher m=p.matcher(str);
boolean f=m.find();
StringBuffer sb=new StringBuffer();
while(f) {
m.appendReplacement(sb,"");
f=m.find();
}
m.appendTail(sb);
System.out.println(sb.toString());
//jdk1.4以上
import java.uti.regex.*;
String str="123(456(789";
String str1="\(";
java.util.regex.Pattern p=Pattern.compile(str1);
Matcher m=p.matcher(str);
boolean f=m.find();
StringBuffer sb=new StringBuffer();
while(f) {
m.appendReplacement(sb,"");
f=m.find();
}
m.appendTail(sb);
System.out.println(sb.toString());
|
这样:
String str="adfad(2sas(1dffdas";
str=str.replaceAll("[(]","");
System.out.println(str);
String str="adfad(2sas(1dffdas";
str=str.replaceAll("[(]","");
System.out.println(str);
|
public static String replace(String str, String strOld, String strNew)
{
int fromIndex = 0;
int newstrLength = strNew.length();
int oldstrLength = strOld.length();
int strIndex = str.indexOf(strOld,fromIndex);
while( strIndex != -1)
{
str = str.substring(0,strIndex) + strNew + str.substring(strIndex+oldstrLength);
fromIndex = (strIndex + newstrLength);
strIndex = str.indexOf(strOld,fromIndex);
}
return str;
}
希望对你有帮助.
{
int fromIndex = 0;
int newstrLength = strNew.length();
int oldstrLength = strOld.length();
int strIndex = str.indexOf(strOld,fromIndex);
while( strIndex != -1)
{
str = str.substring(0,strIndex) + strNew + str.substring(strIndex+oldstrLength);
fromIndex = (strIndex + newstrLength);
strIndex = str.indexOf(strOld,fromIndex);
}
return str;
}
希望对你有帮助.