我想在java中的字符串中添加转义字符"'"
(单引号),但仅当使用正则表达式出现奇数时
对于Ex:
"string's property"
类似,则输出应为"string''s property"
"string''s property"
类似,则输出应为"string''s property"
答案 0 :(得分:1)
答案 1 :(得分:0)
试试这段代码(偶数)。
public static void main(String[] args) {
String str = "a''''''b";
str = str.replaceAll("[^']'('')*[^']", "###");
System.out.println(str);
}
然后尝试这个(奇数)。
public static void main(String[] args) {
String str = "a'''''''b";
str = str.replaceAll("[^']'('')*[^']", "###");
System.out.println(str);
}
答案 2 :(得分:0)
试试这个:
// input that will be replaced
String replace = "string's property";
// input that won't be replaced
String noReplace = "string''s property";
// String representation of the Pattern for both inputs
// |no single quote before...
// | |single quote
// | | |... no single quote after
String pattern = "(?<!')'(?!')";
// Will replace found text with main group twice --> found
System.out.println(replace.replaceAll(pattern, "$0$0"));
// Will replace found text with main group twice --> not found, no replacement
System.out.println(noReplace.replaceAll(pattern, "$0$0"));
输出:
string''s property
string''s property