匹配前后字母条件的字符串 replaceALL
String replaceALL with conditions on letters before and after the match
我正在从文本文件中读取字符串
示例:密西西比州是一个有很多系统的州吗?
我正在尝试使用全部替换将所有 "s" 和 "S" 替换为相同大小写的 "t" 或 "T" 除非在单词的开头并且除非在 "s" 或 "S" 之前或之后还有另一个 "s" 或 "S".
预期输出:密西西比州是一个有很多系统的州吗?
我试过了...
.replaceAll("[^sStT](?!\b)S", "T").replaceAll("[^SstT](?!\b)s", "t");
输出是..."t Mtstsippi a State where there are many Sttet?"
您可以通过两次 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")
);
我知道已经有一个可以接受的答案,但这里有另一种方法可以使用一些 java hack 和否定 lookbehind/after.
来实现你想要的
String s = "Is Mississippi a State where there are a lot of Systems?";
s = s.replaceAll("(?<![ sS])(s|S)(?![sS])", Character.isUpperCase("".charAt(0)) ? "T" : "t");
System.out.println(s); // It Mississippi a State where there are a lot of Syttemt?
我正在从文本文件中读取字符串
示例:密西西比州是一个有很多系统的州吗?
我正在尝试使用全部替换将所有 "s" 和 "S" 替换为相同大小写的 "t" 或 "T" 除非在单词的开头并且除非在 "s" 或 "S" 之前或之后还有另一个 "s" 或 "S".
预期输出:密西西比州是一个有很多系统的州吗?
我试过了...
.replaceAll("[^sStT](?!\b)S", "T").replaceAll("[^SstT](?!\b)s", "t");
输出是..."t Mtstsippi a State where there are many Sttet?"
您可以通过两次 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")
);
我知道已经有一个可以接受的答案,但这里有另一种方法可以使用一些 java hack 和否定 lookbehind/after.
来实现你想要的String s = "Is Mississippi a State where there are a lot of Systems?";
s = s.replaceAll("(?<![ sS])(s|S)(?![sS])", Character.isUpperCase("".charAt(0)) ? "T" : "t");
System.out.println(s); // It Mississippi a State where there are a lot of Syttemt?