正则表达式中的否定字符 [英] Negate characters in Regular Expression

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

问题描述

如何编写符合以下条件的正则表达式?

How would I write a regular expression that matches the following criteria?

  • 没有数字
  • 无特殊字符
  • 没有空格

在一个字符串中

推荐答案

字符类 [^ ] 内的脱字符是大多数正则表达式实现(Perl、.NET、Ruby、Javascript 等)常见的否定运算符.所以我会这样做:

The caret inside of a character class [^ ] is the negation operator common to most regular expression implementations (Perl, .NET, Ruby, Javascript, etc). So I'd do it like this:

[^\W\s\d]

  • ^ - 匹配任何不在字符类中的内容
  • \W - 匹配非单词字符(单词字符将被定义为 a-z、A-Z、0-9 和下划线).
  • \s - 匹配空格(空格、制表符、回车、换行)
  • \d - 匹配 0-9
  • 或者您可以采取另一种方法,只包含您想要的内容:

    Or you can take another approach by simply including only what you want:

    [A-Za-z]
    

    这里的主要区别在于第一个将包含下划线.那,它展示了一种用您正在思考的相同术语来编写表达式的方法.但是,如果您反过来考虑包含字符而不是排除它们,那么有时这会使正则表达式更易于阅读.

    The main difference here is that the first one will include underscores. That, and it demonstrates a way of writing the expression in the same terms that you're thinking. But if you reverse you're thinking to include characters instead of excluding them, then that can sometimes result in an easier to read regular expression.

    我并不完全清楚您不想要哪些特殊字符.但我写了两种解决方案,以防万一一个更适合你.

    It's not completely clear to me which special characters you don't want. But I wrote out both solutions just in case one works better for you than the other.

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

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