java - 如何替换引号之间出现的任何单词

标签 java regex

我需要能够替换出现在单引号之间的所有单词“and”。例如将字符串中的“and”替换为“XXX”:

这个和那个“与你和我以及其他人”而不是“她和他”

结果:

这个和那个“和你 XXX 我 XXX 其他人”而不是“她 XXX 他”

我已经能够想出几乎适用于所有情况的正则表达式,但是我在两组引用文本之间的“和”失败了。

我的代码:

String str = "This and that 'with you and me and others' and not 'her and him'";

String patternStr = ".*?\\'.*?(?i:and).*?\\'.*";
Pattern pattern= Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.matches());
while(matcher.matches()) {
    System.out.println("in matcher");
    str = str.replaceAll("(?:\\')(.*?)(?i:and)(.*?)(?:\\')", "'$1XXX$2'");
    matcher = pattern.matcher(str);
}

System.out.println(str);

最佳答案

试试这段代码:

str = "This and that 'with you and me and others' and not 'her and him'";
Matcher matcher = Pattern.compile("('[^']*?')").matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
   matcher.appendReplacement(sb, matcher.group(1).replaceAll("and", "XXX"));
}
matcher.appendTail(sb);
System.out.println("Output: " + sb);

输出

Output: This and that 'with you XXX me XXX others' and not 'her XXX him'

关于java - 如何替换引号之间出现的任何单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5888124/

相关文章:

java - 如何读取键名中带有 ":"冒号的属性

java - jUnit,Mockito。如何确保抽象类中的方法(模板方法)调用抽象钩子(Hook)方法?

java - 每 x 毫秒执行一次的代码,可更改

java - 如何在 android studio 中的给定 XML 布局文件中使用 Java 动态添加按钮?

regex - 通过perl从字符串中提取数据

java - 如何在我的 Cordova/Phonegap 应用程序中从 JavaScript 调用 Java 函数?

python - 在推文中查找表情符号作为整个簇而不是单个字符

regex - 转义正则表达式中的正斜杠

Python re.sub 问题

C# 使用正则表达式提取单词