← 学习库 Speech and Language Processing 本册目录

2.1.5 Advanced Operators

REExpansionMatchExample Patterns
\d[ 0 -9 ]any digitParty_of_5
\D[ ^0-9 ]any non-digitBlue_moon
\w[ a-zA-Z0-9_ ]any alphanumeric or underscoreDaiyu
\w[ ^\w ]a non-alphanumeric!!!
\s[ _\r\t\n\f ]whitespace (space, tab)
\S[ ^\s ]Non-whitespacein_Concord
Figure 2.6 Aliases for common sets of characters.
原书第 28 页

There are also some useful advanced regular expression operators. Fig. 2.6 shows some useful aliases for common ranges, which can be used mainly to save typing. Besides the Kleene * and Kleene +, we can also use explicit numbers as counters, by enclosing them in curly brackets. The regular expression / {3} / means “exactly 3 occurrences of the previous character or expression”. So /a\.\{24\}z/ will match a followed by 24 dots followed by z (but not a followed by 23 or 25 dots followed by a z).

A range of numbers can also be specified; so / {n, m} / specifies from n to m occurrences of the previous char or expression, while / {n, } / means at least n occurrences of the previous expression. REs for counting are summarized in Figure 2.7.

REMatch
*zero or more occurrences of the previous char or expression
+one or more occurrences of the previous char or expression
?exactly zero or one occurrence of the previous char or expression
{n}n occurrences of the previous char or expression
{n,m}from n to m occurrences of the previous char or expression
{n,}at least n occurrences of the previous char or expression
Figure 2.7 Regular expression operators for counting.

Finally, certain special characters are referred to by special notation based on the backslash (\). The most common of these are the newline character \n and the tab character \ t. To refer to characters that are special themselves (like ., *, [, and \), precede them with a backslash, (i.e., / \ . /, / \ */ , / \ [ /, and / \ /).

| RE | Match | Example Patterns Matched |

| --- | --- | --- |

| $ \backslash $ $ \cdot $ $ \backslash $ $ \cdot $ $ \backslash $ $ \cdot $\n\n\n\nt | an asterisk “*”\na period “.”\na question mark\na newline\na tab | “K_ $ \cdot $A*P*L*A*N”\n“Dr_Livingston, I presume”\n“Why don’t they come and lend a hand?” |

| | | |

Figure 2.8 Some characters that need to be backslashed.

The reader should consult Appendix A for further details of regular expressions, and especially for the differences between regular expressions in Perl, UNIX, and Microsoft Word.

← 2.1.4 A More Complex Example2.1.6 Regular Expression Substitution, Memory, and ELIZA →