繁体   English   中英

使用正则表达式检查特殊字符Java

[英]Using a regex to check for special characters java

我想检查一个单词是否包含特殊字符并将其删除。 可以说我有String word = "hello-there" ,我想遍历并检查该单词是否不包含字母,然后删除该特殊字符并连接该单词。 因此,我想使用正则表达式将hello-there转换为hellothere 我已经尝试过了,但是我似乎无法弄清楚如何检查正则表达式中字符串的各个字符。

public static void main(String[] args){
String word = "hello-there";

for(int i = 0; i < word.length(); i++)
{
    if(word.charAt(i).matches("^[a-zA-Z]+"))

但是最后一个if语句不起作用。 有人知道该怎么办吗?

您可以使用以下正则表达式 ,它将匹配任何字符,而不是小写或大写字母。

[^a-zA-Z]+ 

参见正则表达式演示

Java演示

class RegEx {
    public static void main(String[] args) {
        String s = "hello-there";
        String r = "[^a-zA-Z]+";
        String o = s.replaceAll(r, "");
        System.out.println(o); //-> hellothere
    }
}

暂无
暂无

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

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