简体   繁体   English

如何删除任何非字母数字字符?

[英]How to remove any non-alphanumeric characters?

I want to remove any non-alphanumeric character from a string, except for certain ones. 我想从字符串中删除任何非字母数字字符,除了某些字符串。

StringUtils.replacePattern(input, "\\\\p{Alnum}", "");

How can I also exclude those certain characters, like .-; 我怎样才能排除那些特定的字符,比如.-; ?

Use the not operator ^ : 使用not运算符^

[^a-zA-Z0-9.\-;]+

This means "match what is not these characters". 这意味着“匹配不是这些字符”。 So: 所以:

StringUtils.replacePattern(input, "[^a-zA-Z0-9.\\-;]+", "");

Don't forget to properly escape the characters that need escaping: you need to use two backslashes \\\\ because your regex is a Java string. 不要忘记正确转义需要转义的字符:你需要使用两个反斜杠\\\\因为你的正则表达式是一个Java字符串。

You could negate your expression; 你可以否定你的表达;

\p{Alnum}

By placing it in a negative character class: 将它放在负字符类中:

[^\p{Alnum}]

That will match any non-alpha numeric characters, you could then replace those with "" . 这将匹配任何非字母数字字符,然后您可以用""替换那些。 if you wanted to allow additional characters you can just append them to the character class, eg: 如果你想允许其他字符,你可以将它们附加到字符类,例如:

[^\p{Alnum}\s]

will not match white space characters ( \\s ). 将不匹配空格字符( \\s )。

If you where to replace 如果你在哪里更换

[^\p{Alnum}.;-]

with "" , these characters will also be allowed: . "" ,这些字符也将被允许: . , ; ; or - . -

StringUtils uses Java's standard Pattern class under the hood. StringUtils使用Java的标准Pattern类。 If you don't want to import Apache's library and want it to run quicker (since it doesn't have to compile the regex each time it's used) you could do: 如果您不想导入Apache的库并希望它更快地运行(因为它不必在每次使用时编译正则表达式),您可以执行以下操作:

private static final Pattern NO_ODD_CHARACTERS = Pattern.compile("[^a-zA-Z0-9.\\-;]+");

...

String cleaned = NO_ODD_CHARACTERS.matcher(input).replaceAll("");

You mean something like StringUtils.replacePattern(input, "[^az\\.\\-]+", ""); 你的意思是像StringUtils.replacePattern(input, "[^az\\.\\-]+", ""); - even though I don't exactly whether StringUtils uses a special RegEx syntax. - 即使我不确定StringUtils是否使用特殊的RegEx语法。

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

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