正则表达式仅删除特殊字符而不删除其他语言字母

Regex to remove only special characters and not other language letters

我使用正则表达式从名称中删除特殊字符。该表达式将删除除英文字母以外的所有字母。

public static void main(String args[]) {
    String name = "Özcan Sevim.";
    name = name.replaceAll("[^a-zA-Z\s]", " ").trim();
    System.out.println(name);
}

输出:

zcan Sevim

预期输出:

Özcan Sevim 

我这样做的结果很糟糕,正确的方法是根据 ASCII 码删除特殊字符,这样其他字母就不会被删除,有人可以帮我用一个只删除特殊字符的正则表达式吗字符。

您可以使用 \p{IsLatin}\p{IsAlphabetic}

name = name.replaceAll("[^\p{IsLatin}]", " ").trim();

或者要删除标点符号,只需使用 \p{Punct},如下所示:

name = name.replaceAll("\p{Punct}", " ").trim();

输出

Özcan Sevim

查看 Summary of regular-expression constructs 的完整列表并使用可以帮助您的列表。

使用 [\W+] 或 "[^a-zA-Z0-9]" 作为正则表达式来匹配任何特殊字符,并使用 String.replaceAll(regex, String) 将 spl 字符替换为空字符串。请记住,String.replaceAll 的第一个参数是正则表达式,您必须使用反斜杠对其进行转义,以将 em 视为文字字符。

 String string= "hjdg$h&jk8^i0ssh6";
        Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
        Matcher match= pt.matcher(string);
        while(match.find())
        {
            String s= match.group();
        string=string.replaceAll("\"+s, "");
        }
        System.out.println(string);

为此使用 Guava CharMatcher :) 它会更容易阅读和维护。

name = CharMatcher.ASCII.negate().removeFrom(name);