字符串replaceALL,包含匹配前后字母的条件

时间:2016-04-04 19:11:24

标签: java regex conditional replaceall

我正在从文本文件中读取字符串

示例:密西西比州是一个拥有大量系统的州吗?

我正在尝试使用replace all替换所有“s”& “S”具有相同的“t”或“T”,除非在单词的开头,除非在“s”或“S”之前或之后有另一个“s”或“S”。

预计输出:密西西比州是一个有很多Syttemt的国家吗?

我试过......

.replaceAll("[^sStT](?!\\b)S", "T").replaceAll("[^SstT](?!\\b)s", "t"); 

输出是......“Mtstsippi是一个有许多Sttet的州吗?”

2 个答案:

答案 0 :(得分:1)

您可以通过两次replaceAll来电来完成此操作。一个用于s -> t,另一个用于S -> T

您可以使用后视(?<=regex)和前瞻(?=regex)组来查找模式而不替换其内容。

后视将检查s之前的字符是否不在字符[^<list>]列表中。此列表包含起始字符^sS以及tT和空格\\s

(?<=[^^\\ssStT])

前瞻会做类似的检查,但只验证下一个字符不是sS

(?=[^sS])

把这一切放在一起:

String test = "Is Mississippi a State where there are a lot of Systems?";
System.out.println(test
        .replaceAll("(?<=[^^\\ssStT])s(?=[^sS])","t")
        .replaceAll("(?<=[^^\\ssStT])S(?=[^sS])","T")
);

答案 1 :(得分:1)

我知道已经有一个已接受的答案,但这是另一种方法,可以使用一点java黑客和负面的lookbehind / after来实现你想要的东西。

String s = "Is Mississippi a State where there are a lot of Systems?";
s = s.replaceAll("(?<![ sS])(s|S)(?![sS])", Character.isUpperCase("$1".charAt(0)) ? "T" : "t");
System.out.println(s); // It Mississippi a State where there are a lot of Syttemt?
相关问题