如何用两个单引号替换奇数单引号

时间:2014-03-05 14:42:03

标签: java regex string

我想在java中的字符串中添加转义字符"'"(单引号),但仅当使用正则表达式出现奇数时

对于Ex:

  1. 如果字符串与"string's property"类似,则输出应为"string''s property"
  2. 如果字符串与"string''s property"类似,则输出应为"string''s property"

3 个答案:

答案 0 :(得分:1)

试试这个:

\'(\')?

演示(替换为'

http://regexr.com?38eeh

答案 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