如果我们有单引号('),则在下面的行中,我们必须将其替换为' ||''''但如果我们有两次单引号('')那么它应该是原样。
我尝试下面的一段代码,但没有给我正确的输出。
代码段:
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.
正则表达式正在用 child' ||&#39替换 孩子 ;'' S 即可。的 子'' S 应保持原样。
答案 0 :(得分: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, "'||'''"));
答案 1 :(得分: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, "'||'''"));
输出:
Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us.
根据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, "'||'''"));