繁体   English   中英

如何替换仅出现一次的子字符串,而连续两次或多次排除子字符串呢?

[英]how can I replace substring that occurs only once while excluding substring two or more times in a row?

有什么办法可以在Java中执行以下操作?

String s = "acdaaefacaa";
String b = s.replaceLikeMethod("a", "");

b变成“ cdaaefcaa”。 基本上将出现的第一个字符串"a"替换为另一个""除非"a"连续出现两次或多次。

您可以使用正则表达式来实现。 您想要的功能是

  1. 负LookBehind (?<!foo)匹配模式,除非foo恰好出现在前面。
  2. 负面的前瞻。 (?!foo)匹配模式,除非之后立即发生foo

基本上,您需要同时使用相同的字符串作为匹配和模式字符串。 例如

String pattern = "(?<!foo)foo(?!foo)";

或者轻松替换为运行时已知的字符串,例如"a"

String pattern = "(?<!foo)foo(?!foo)".replace("foo", "a");

最后,替换为:

String b = s.replaceAll(pattern, "");

使用此正则表达式: ((?<!a)a(?!a)) 它使用负向前瞻和向后搜索。 它与每个前面没有的a匹配,后面跟另一个a

测试:

String input = "acdaaefacaa";
String output = input.replaceAll("((?<!a)a(?!a))", "");
System.out.println(output);

输出:

cdaaefcaa

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM