在Java中,可以使用一个表达式来忽略特殊符号、数字和空格。

huangapple go评论124阅读模式
英文:

One expression to ignore special symbols, numbers, and spacing? Java

问题

以下是我已经完成的部分:

userSent = userSent.replaceAll("\\s+", "")
                    .replaceAll("[^a-zA-Z0-9]", "")
                    .replaceAll("[0-9]", "");

如果可能的话,我想用一个表达式来简化这个过程,使用Java语言,非常感谢。

英文:

What I have so far is:

userSent = userSent.replaceAll("\\s+", ""); //replaces all spaces with no spacing
userSent = userSent.replaceAll("[^a-zA-Z0-9]", ""); //remove all special characters
userSent = userSent.replaceAll("[0-9]", ""); //remove all numbers from string

I would like to simplify this to one expression if possible using Java, thanks a bunch.

答案1

得分: 1

这三个替换等同于以下内容:

userSent = userSent.replaceAll("[^a-zA-Z]", "");

(被视为“非字母”的字符集包括数字和空格。)

然而,我怀疑这可能不是你实际想要的,因为它会删除所有不在拉丁字母表中的字符,并将它们全部混合成一个单一的“单词”。这真的是你想要的吗?在我看来,这与你问题标题中描述的问题不匹配。

我的建议是,在尝试将它们组合成一个单一的正则表达式之前,确保这三个替换确实实现了你想要的效果(换句话说...在组合之前测试它们的组合效果)。

英文:

Those three replaces are equivalent to this:

userSent = userSent.replaceAll("[^a-zA-Z]", "");

<sup>(The set of characters that are "not a letter" includes numbers and spaces.)</sup>

However, I suspect that this is not what you actually want because it removes every character that is not in the Latin alphabet and mashes them all into a single "word". Is that really what you want? (To my mind, it doesn't match the problem description in your Question's title.)

My advice would be to make sure that the 3 replaces do what you actually want (in other words ... test them in combination) before you try to combine them into a single regex.

huangapple
  • 本文由 发表于 2020年10月19日 08:35:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64419706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定