正则表达式用'||'''替换'(单引号一次但不是''(单引号两次)

San*_*ani 5 java regex

在下面的行中,如果我们有单引号(')那么我们必须用'||'''替换它,但如果我们有两次单引号('')那么它应该是原样.

我尝试下面的一段代码没有给我正确的输出.

代码片段:

static String replaceSingleQuoteOnly = "('(?!')'{0})";
String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us.";
System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));
Run Code Online (Sandbox Code Playgroud)

上述代码的实际输出:

Your Form xyz doesn'||'''t show the same child''||'''s name as the name in your account with us.
Run Code Online (Sandbox Code Playgroud)

预期结果:

Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us.
Run Code Online (Sandbox Code Playgroud)

正则表达式替换子"是孩子""||"'的.孩子 应该保持原样.

Dar*_*hta 5

你可以使用lookarounds,例如:

String replaceSingleQuoteOnly = "(?<!')'(?!')";
String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us.";
System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));
Run Code Online (Sandbox Code Playgroud)


Pav*_*ngh 4

'在后面添加否定外观以确保另一个字符之前没有字符'并删除额外的捕获组()

所以使用(?<!')'(?!')

    String replaceSingleQuoteOnly = "(?<!')'(?!')";
    String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us.";
    System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));
Run Code Online (Sandbox Code Playgroud)

输出 :

Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us.
Run Code Online (Sandbox Code Playgroud)

根据Apostrophe用法,您可以简单地使用(?i)(?<=[a-z])'(?=[a-z])来查找'被字母包围的

    String replaceSingleQuoteOnly = "(?i)(?<=[a-z])'(?=[a-z])";
    String line2 = "Your Form xyz doesN'T show the same child''s name as the name in your account with us.";
    System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));
Run Code Online (Sandbox Code Playgroud)