ReplaceAll 仅替换第一次出现的子字符串
ReplaceAll replaces only first occurance of substring
我想用 '
替换第一个括号内的 "
。第二个括号内的子字符串应保持不变。示例:
String test = "(\"test1\", \"test2\") (\"test3\", \"test4\")"; //wanted output is ('test1', 'test2') ("test3", "test4")
String regex = "(^[^\)]*?)\"(.*?)\"";
test = test.replaceAll(regex, "''");
System.out.println(test); // output is ('test1', "test2") ("test3", "test4")
test = test.replaceAll(regex, "''");
System.out.println(test); // output is ('test1', 'test2') ("test3", "test4")
为什么第一次调用 replaceAll 时,"
周围的 test2 没有被替换?
这是使用边界匹配器的好用例\G
:
String test = "(\"test1\", \"test2\") (\"test3\", \"test4\")";
final String regex = "(^\(|\G(?!^),\h*)\"([^\"]+)\"";
test = test.replaceAll(regex, "''");
System.out.println(test);
//=> ('test1', 'test2') ("test3", "test4")
\G
断言位置 在上一个匹配的末尾 或第一个匹配的字符串的开头
我想用 '
替换第一个括号内的 "
。第二个括号内的子字符串应保持不变。示例:
String test = "(\"test1\", \"test2\") (\"test3\", \"test4\")"; //wanted output is ('test1', 'test2') ("test3", "test4")
String regex = "(^[^\)]*?)\"(.*?)\"";
test = test.replaceAll(regex, "''");
System.out.println(test); // output is ('test1', "test2") ("test3", "test4")
test = test.replaceAll(regex, "''");
System.out.println(test); // output is ('test1', 'test2') ("test3", "test4")
为什么第一次调用 replaceAll 时,"
周围的 test2 没有被替换?
这是使用边界匹配器的好用例\G
:
String test = "(\"test1\", \"test2\") (\"test3\", \"test4\")";
final String regex = "(^\(|\G(?!^),\h*)\"([^\"]+)\"";
test = test.replaceAll(regex, "''");
System.out.println(test);
//=> ('test1', 'test2') ("test3", "test4")
\G
断言位置 在上一个匹配的末尾 或第一个匹配的字符串的开头