【问题标题】:How to remove 3 or more consecutive letters in java into 2 consecutive letters?如何将java中的3个或更多连续字母删除为2个连续字母?
【发布时间】:2016-09-02 12:31:06
【问题描述】:

我正在尝试处理带有重复字符的字符串,以便在字典中找到正确的单词。

我必须使用的方法是找到具有 3 个或更多连续字母的单词并将它们删除为 2 个连续字母。

然后我会在字典中查找这个词是否存在。如果该词不存在,那么我必须将两个连续的字母删除为仅 1 个字母。

例子:

gooooooood -> good (this existis)
awesooooome -> awesoome (this doesn't exist) -> awesome (this exists)
aaawwwesooooooommmme -> aawwesoomme (this doesn't exist) -> awesome (this exists)

我正在使用 JAVA,并且我已经在使用这个正则表达式来获取字符串中包含 3 个或更多重复字母的单词:

Pattern p = Pattern.compile("\\b\\w*(\\w)\\1{2}\\w*");

【问题讨论】:

  • “gggoood”->“ggood”->“神”?
  • Sasha Salauyou,说得很好。在那种情况下,我想我应该总是先唱辅音,然后唱元音。 “gggoood”->“ggoood”->“好”->“好”
  • 这是否相当于从 3 中删除一个,从 2 中删除一个?
  • @user1201779 “puuuppy” -> “puuuppy” -> “puuupy” -> “puupy” -> “pupy”?
  • @user1201779 如您所见,应在所有可能的组合中检查“n 次重复”->“2 次重复”->“1 次重复”的变体以获得可靠的输出。

标签: java regex replace repeat letters


【解决方案1】:

您可以使用这个正则表达式(“纯版本”):

(\b\w*?)(\w)\2{2,}(\w*)

字符串版本:

"(\\b\\w*?)(\\w)\\2{2,}(\\w*)"

你应该使用replaceAll(regex, "$1$2$2$3")

说明

(\b\w*?) // capture group 1 is lazy
(\w)     // capture group 2 captures the first occurrence of the char
\2{2,}   // char may occur 2 or more times...
(\w*)    // capture group 3

注意,替换中的$number指的是对应捕获组的内容。

【讨论】:

    【解决方案2】:

    你也可以这样做:

    Pattern pattern = Pattern.compile("(\\w)\\1{2,}");
    System.out.println(pattern.matcher("gooooooood").replaceAll("$1$1"));
    System.out.println(pattern.matcher("awesooooome").replaceAll("$1$1"));
    System.out.println(pattern.matcher("aaawwwesooooooommmme").replaceAll("$1$1"));
    

    输出:

    good
    awesoome
    aawwesoomme
    

    对于第二步,您可以这样做:

    Pattern pattern2 = Pattern.compile("(\\w)\\1");
    System.out.println(pattern2.matcher("awesoome").replaceAll("$1"));
    System.out.println(pattern2.matcher("aawwesoomme").replaceAll("$1"));
    

    输出:

    awesome
    awesome
    

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 1970-01-01
      • 2014-02-26
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多