使用Java从字符串中删除双字母 [英] Remove doubled letter from a string using java

查看:63
本文介绍了使用Java从字符串中删除双字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Java中的regex操作从字符串中删除双精度字母.例如:PRINCEE-> PRINCE苹果-> APLE

I need to remove a doubled letter from a string using regex operations in java. Eg: PRINCEE -> PRINCE APPLE -> APLE

推荐答案

简单解决方案(删除重复的字符)

赞:

final String str = "APPLEE";
String replaced = str.replaceAll("(.)\\1", "$1");
System.out.println(replaced);

输出:

APLE

不仅限于所有字母,仅包括字母

@Jim正确注释时,以上内容匹配任何双字符,而不仅仅是字母.以下是一些仅与字母匹配的变体:

Not just any Chracters, Letters only

As @Jim comments correctly, the above matches any double character, not just letters. Here are a few variations that just match letters:

// the basics, ASCII letters. these two are equivalent:
str.replaceAll("([A-Za-z])\\1", "$1");
str.replaceAll("(\\p{Alpha})\\1", "$1");

// Unicode Letters
str.replaceAll("(\\p{L})\\1", "$1");

// anything where Character.isLetter(ch) returns true
str.replaceAll("(\\p{javaLetter})\\1", "$1");

参考文献:

其他参考:

  1. 字符.isLetter(ch) (javadocs)
  2. 字符 形式 Character.isXyz(char)启用名为 \ p {javaXyz} (请注意大写).该机制是中所述模式javadocs
  3. Unicode块和类别可以还与 \ p \ P 的构造与Perl中的一样. \ p {prop} 如果输入具有属性道具,而 \ P {prop} 可以如果输入内容不匹配财产.此机制是
  1. Character.isLetter(ch) (javadocs)
  2. any method in Character of the form Character.isXyz(char) enables a pattern named \p{javaXyz} (mind the capitalization). This mechanism is described in the Pattern javadocs
  3. Unicode blocks and categories can also be matched with the \p and \P constructs as in Perl. \p{prop} matches if the input has the property prop, while \P{prop} does not match if the input has that property. This mechanism is also described in the Pattern javadocs

这篇关于使用Java从字符串中删除双字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆