java - 将 ' (single quote once) but not ' '(单引号两次)替换为 '||' '' 的正则表达式

标签 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, "'||'''"));

以上代码的实际输出:

Your Form xyz doesn'||'''t show the same child''||'''s name as the name in your account with us.

预期结果:

Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us.

Regular expression is replacing child''s with child''||'''s. child''s should remain as it is.

最佳答案

您可以使用 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, "'||'''"));

关于java - 将 ' (single quote once) but not ' '(单引号两次)替换为 '||' '' 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877489/

相关文章:

java - Maven 没有将所有依赖项添加到 jar

java - servlet如何处理来自同一个jsp页面的多个请求

Java:当 ConcurrentSkipListSet 的 Comparator (a, b) == 0 时会发生什么?

Java字符转换为UTF-8

regex - grep 带有字符串变量和正则表达式

javascript - float 的正则表达式

java - 如何将这两种方法合二为一?

C# 正则表达式 - 替换为自身

javascript - 如何替换脚本源中的url

regex - 带前缀的有效十进制或十六进制的正则表达式