最新消息:VPS服务器又从fzhost.net换回Linode了,主题仍用朋友推荐的大前端D8

【教程】详解Python正则表达式之: [] bracket 中括号 匹配某集合内的字符

Python re crifan 1025浏览 0评论

Python 2.7手册中的官方解释为:

[]

Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. Special characters are not active inside sets. For example, [akm$] will match any of the characters 'a', 'k', 'm', or '$'; [a-z] will match any lowercase letter, and [a-zA-Z0-9] matches any letter or digit. Character classes such as \w or \S (defined below) are also acceptable inside a range, although the characters they match depends on whether LOCALE or UNICODE mode is in force. If you want to include a ']' or a '-' inside a set, precede it with a backslash, or place it as the first character. The pattern []] will match ']', for example.

You can match the characters not within a range by complementing the set. This is indicated by including a '^' as the first character of the set; '^' elsewhere will simply match the '^' character. For example, [^5] will match any character except '5', and [^^] will match any character except '^'.

Note that inside [] the special forms and special characters lose their meanings and only the syntaxes described here are valid. For example, +, *, (, ), and so on are treated as literals inside [], and backreferences cannot be used inside [].

下面就来详细解释具体的含义:

1.中括号 [] 用来匹配一组的字符,一个集合内的字符,其中,此处所说的组或者集合,是你自己写在中括号内的,自己定义的组合。

最简单的举例为,比如你就只需要匹配字符abc中的任意一个字符,那么此处的abc,就是你自己定义的集合。

2. 另外最常见的如,匹配小写字母a到z中任何一个,那就可以从a到z,都列出来。当前这样写很蠢,更加正常的做法是写成,起始字符,中间是短横线’-‘分隔,加上结束字符,即写成a-z,就表示a到z中的所有的字符了。

转载请注明:在路上 » 【教程】详解Python正则表达式之: [] bracket 中括号 匹配某集合内的字符

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
14 queries in 0.225 seconds, using 10.26MB memory