替换与正则表达式中的字符不匹配的字符 [英] replace characters which do not match with the ones in a regex

查看:207
本文介绍了替换与正则表达式中的字符不匹配的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式:

private static final String SPACE_PATH_REGEX ="[a-z|A-Z|0-9|\\/|\\-|\\_|\\+]+";

我检查我的字符串是否与此正则表达式匹配,如果不是,我想替换所有不是的字符在这里,用_。

I check if my string matches this regex and IF NOT, i want to replace all characters which are not here, with "_".

我尝试过:

private static final String SPACE_PATH_REGEX_EXCLUDE =
        "[~a-z|A-Z|0-9|\\/|\\-|\\_|\\+]+";
if (myCompanyName.matches(SPACE_PATH_REGEX)) {
    myNewCompanySpaceName = myCompanyName;
} else{
    myNewCompanySpaceName = myCompanyName.replaceAll(
            SPACE_PATH_REGEX_EXCLUDE, "_");
}

但它不起作用......所以在第二个正则表达式〜 似乎没有省略以下的字符。

but it does not work..., so in the 2nd regex "~" seems to not omit the following chars.

任何想法?

推荐答案

<你的正则表达式中有几个问题(参见 模式规则):


  • 字符类 | 没有特殊含义,在您的情况下应该删除而不替换(除非您希望您的字符类包含文字 | 字符)。

  • 同样,您不需要转义 / _ +

  • - 只有它不是最后一个字符才需要转义

  • 在它只代表自己的字符类中也没有特殊含义

  • 您将要使用 ^ 否定字符组的内容。

  • inside a character class | has no special meaning and should be removed without replacement in your case (unless you want your character class to include the literal | character).
  • Similarly you don't need to escape /, _ and + inside a character class.
  • - only needs to be escape if it's not the last character
  • ~ also has no special meaning in a character class it just represents itself
  • you will want to use ^ to negate the content of a character group.

您也可以跳过第一个 matches() check,因为 replaceAll()调用将返回未修改的String,如果没有任何匹配的话。保持它(和第二个正则表达式)仅用于引入另一个可以隐藏错误的地方(例如,您可能会意外更新一个正则表达式,而不是另一个正则表达式)。

You can also skip the first matches() check, as the replaceAll() call will return an unmodified String if nothing matches anyway. Keeping it (and the second regular expression) only serves to introduces another place where bugs could hide (for example you could accidentally update one regex, but not the other).

这篇关于替换与正则表达式中的字符不匹配的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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