字符类,顾名思义就是某一类字符或者将某些字符分成一类。正则表达式中的字符类用一对方括号([])来表示,比如 [abcd] 或 [0123456789]。事实上,字符类所暗含的意思就是选择性,即“多选一”――不管方括号中包含多少个字符,一对方括号一次只能匹配一个字符。

在正则表达式中,更明显具有选择性的就是交替选择(alternation)。交替选择以竖线(|)表示,竖线两侧的模式可以称之为选项。交替选择必须与一对圆括号连用,即通过圆括号将所有以竖线分隔的选项包围起来。交替选择模式中至少要有两个选项(一个竖线)――此时的选择性可以称之为“二选一”,但也可以包含多个选项――此时的选择性则可以称之为“多选一”。但这里的“多选一”与字符类中的“多选一”不同,这里是指“从多个选项中的选择一个选项”,而不是“从多个字符中选择一个字符”。而选项则可以是任何正则表达式模式。

举例来说,如果用字符类

[a-z]

来测试字符串 abcde,那每次只能返回一个字母,分别是 a、b、c、d 和 e。而如果用交替选择

(abc|de)

来测试同一个字符串,那么(每次都)将返回字符序列 abc。而如果使用另一个交替选择

(\w+|abc)

来测试这个字符串,那么将返回字符序列 abcde。

现在,我们对字符类与交替选择中的选择性就应该非常清楚了。



朋友们的留言

  1. UGG Sheepskin Boots Australia | 09月 19th, 2011 at 09:14

    Your article is useful for me. It is a good article.

    Reply to this comment
  2. UGG Highkoo Sale | 09月 27th, 2011 at 10:42

    Comfortably, the article is really the sweetest on this precious topic.

    Reply to this comment
  3. Air Yeezy | 09月 27th, 2011 at 22:27

    No man can be brave who considers pain the greatest evil of life; or temperate , who regards pleasure as the highest good. (Cicero, ancient Roman statsman)

    Reply to this comment
  4. Jordan Fusion | 10月 5th, 2011 at 15:35

    You may be more happy than pinces,if you will be more virtuous.

    Reply to this comment

我来说两句儿

可以在留言中使用以下标签 :<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree