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

2.1.4 A More Complex Example

Let's try out a more significant example of the power of REs. Suppose we want to build an application to help a user buy a computer on the Web. The user might want "any PC with more than 500 MHz and 32 Gb of disk space for less than 1000". In order to do this kind of retrieval we will first need to be able to look for expressions like $ 500 MHz $

原书第 27 页

or 32 Gb or Compaq or Mac or $999.99. In the rest of this section we'll work out some simple regular expressions for this task.

First, let's complete our regular expression for prices. Here's a regular expression for a dollar sign followed by a string of digits. Note that Perl is smart enough to realize that $ here doesn't mean end-of-line; how might it know that?

/$ [0-9]+/

Now we just need to deal with fractions of dollars. We'll add a decimal point and two digits afterwards:

$$ /~\\left[0-9\right]+\backslash.\left[0-9\right]\left[0-9\right]/ $$

This pattern only allows $199.99 but not $199. We need to make the cents optional, and make sure we're at a word boundary:

$$ \left/\backslash\mathbf{b}\\left[0-9\right]+(\backslash\cdot\left[0-9\right]\left[0-9\right])?\backslash\mathbf{b}/\right. $$

How about specifications for processor speed (in megahertz = MHz or gigahertz = GHz)? Here's a pattern for that:

$$ \left/{\mathrm{\textbf{b}}[0-9]}\right.+\mathrm{\underline{\emph{b}}}^{*}\left(\mathrm{M H z}\left|\mathrm{[M m]}\right.\right.\mathrm{e g a h e r t z}\left|\mathrm{G H z}\left|\mathrm{[G g]}\right.\right.\mathrm{i g a h e r t z}\left)\mathrm{\textbf{\textit{b}}}/ $$

Note that we use / ☐* / to mean “zero or more spaces”, since there might always be extra spaces lying around. Dealing with disk space (in Gb = gigabytes), or memory size (in Mb = megabytes or Gb = gigabytes), we need to allow for optional gigabyte fractions again (5.5 Gb). Note the use of ? for making the final s optional:

$$ \begin{array}{l}\left/\backslash b[0-9]+\bot\ast(Mb\left|\left[Mm\right]egabytes?\right)\backslash b/\right.\\\left/\backslash b[0-9](\backslash.[0-9]+)?\bot\ast(Gb\left|\left[Gg\right]igabytes?)\backslash b/\right.\right.\end{array} $$

Finally, we might want some simple patterns to specify operating systems and vendors:

$$ \begin{array}{l}/\backslash b(Win95\mid Win98\mid WinNT\mid Windows\_{*}(NT\mid95\mid98\mid2000)?)\backslash b/\\\backslash b(Mac\mid Macintosh\mid Apple)\backslash b/\end{array} $$

← 2.1.3 A Simple Example2.1.5 Advanced Operators →