简体   繁体   English

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

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

Is there any way that I can do the following in java ? 有什么办法可以在Java中执行以下操作?

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

and b becomes "cdaaefcaa". b变成“ cdaaefcaa”。 Basically replace any occurrence of the first string "a" with the other one "" unless "a" appears two or more times in a row. 基本上将出现的第一个字符串"a"替换为另一个""除非"a"连续出现两次或多次。

You can use regex to achieve this. 您可以使用正则表达式来实现。 The features you want are 您想要的功能是

  1. Negative LookBehind (?<!foo) Match pattern unless foo occurs right before. 负LookBehind (?<!foo)匹配模式,除非foo恰好出现在前面。
  2. Negative LookAhead. 负面的前瞻。 (?!foo) Match pattern unless foo occurs right afterwards (?!foo)匹配模式,除非之后立即发生foo

You basically need to use both at the same time with the same string as the string to match and pattern. 基本上,您需要同时使用相同的字符串作为匹配和模式字符串。 Eg 例如

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

Or to easily replace with a string known at runtime like "a" 或者轻松替换为运行时已知的字符串,例如"a"

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

Finally, to replace just do : 最后,替换为:

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

Use this regex: ((?<!a)a(?!a)) . 使用此正则表达式: ((?<!a)a(?!a)) It uses negative lookahead and lookbehind. 它使用负向前瞻和向后搜索。 It matches every a that is not preceded and followed by another a . 它与每个前面没有的a匹配,后面跟另一个a

Test: 测试:

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

Outputs: 输出:

cdaaefcaa cdaaefcaa

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

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