[英]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.