[英]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"
连续出现两次或多次。
您可以使用正则表达式来实现。 您想要的功能是
(?<!foo)
匹配模式,除非foo
恰好出现在前面。 (?!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.