我正在尝试转换以下字符串
Insert into table01 values('abcd01','abcd02','abcd03')
至
Insert into table01 values( 'abcd01', 'abcd02', 'abcd03' )
我的代码:
package layout;
public class String02 {
public String Replace01(String testString) {
String string01 = "";
string01 = testString.replaceAll("\('", "\( ");
string01 = testString.replaceAll("\)", " \)");
string01 = testString.replaceAll(",", ", ");
return string01;
}
public static void main(String[] args) {
String02 app = new String02();
String testString = "Insert into table01 values('abcd01','abcd02','abcd03')";
String s1 = app.Replace01(testString);
System.out.println(s1);
}
}
string01 = testString.replaceAll("\('", "\( ");
string01 = testString.replaceAll("\)", " \)");
string01 = testString.replaceAll(",", ", ");
字符串是不可变的。由于每个replaceAll((语句都会返回一个新字符串,因此不能继续对原始字符串进行操作。
代码应该是:
string01 = testString.replaceAll("\('", "\( '");
string01 = string01.replaceAll("\)", " \)");
string01 = string01.replaceAll(",", ", ");
此外,您的第一个replaceAll(…(语句不正确,因为您在替换字符串中错过了'
。
错误主要是您没有使用string01
进行第二次和第三次替换,而是原始CCD_ 3。(replace(All/First)
不会更改字符串本身,而是生成一个新字符串(。因此,第一个和第二个替代者都失去了。
那么就不需要替换正则表达式了。你可以这样写:
string01 = testString.replace("('", "( '")
.replace(")", " )")
.replace("','", "', '");
您可以使用正则表达式('(?=\))|\,|\()
和replaceAll()
方法捕获组引用$1
:
String testString = "Insert into table01 values('abcd01','abcd02','abcd03')";
String string01 = testString.replaceAll("('(?=\))|\,|\()", "$1 ");
System.out.println(string01);
(...)
:捕获组$1
:捕获组引用|
:OR运算符(?=...)
:在)
之前捕获'
的正向前瞻
输出:
Insert into table01 values( 'abcd01', 'abcd02', 'abcd03' )
如果您在正则表达式方面遇到问题,请考虑回到基础知识。
public class String02 {
public String Replace01(String testString) {
String string01 = "";
char ch;
for(int i=0; i<testString.length(); i++){
ch = testString.charAt(i);
if(ch=='(' || ch==','){
if((i+1)<testString.length() && testString.charAt(i+1)!=' '){
string01 += ch + " ";
continue;
}
}else if (ch==')'){
if((i-1)>=0 && testString.charAt(i-1)!=' '){
string01 += " " + ch;
continue;
}
}
string01 += ch;
}
return string01;
}
public static void main(String[] args) {
String02 app = new String02();
String testString = "Insert into table01 values('abcd01','abcd02','abcd03')";
String s1 = app.Replace01(testString);
System.out.println(s1);
}
}
您也可以使用查找来查找特定的位置,并且在替换中使用单个空格。
(?<=(|',)(?=')|(?<=')(?=))
请参阅此regex演示或Java演示中的位置。
(?<=(|',)(?=')
如果左边是(
或',
,右边是'
,则肯定的后备断言|
或(?<=')(?=))
如果左边是'
,右边是)
,则肯定的后备断言
示例
String s = "Insert into table01 values('abcd01','abcd02','abcd03')";
String result = s.replaceAll("(?<=\(|',)(?=')|(?<=')(?=\))", " ");
System.out.println(result);
输出
Insert into table01 values( 'abcd01', 'abcd02', 'abcd03' )