<h2>要匹配任何一个单词,您可以使用模式<code>(\w+)</code></h2>
<p>假设您正在使用PCRE或类似的工具:</p>
<p><img src="https://i.stack.imgur.com/l69SY.png" alt="enter image description here"/></p>
<p>以上截图摘自本例:<a href="http://regex101.com/r/cU5lC2" rel="noreferrer">http://regex101.com/r/cU5lC2</a></p>
<h2>用<code>(\w+)</code>匹配命令行中的所有单词</h2>
<p>我将使用<a href="http://releases.ubuntu.com/12.10/" rel="noreferrer">Ubuntu 12.10</a>上的<a href="http://www.phpsh.org/" rel="noreferrer">phpsh interactive shell</a>通过名为<a href="http://us2.php.net/preg_match" rel="noreferrer">preg_match</a>的方法演示<a href="http://us2.php.net/pcre" rel="noreferrer">PCRE regex engine</a></p>
<p>启动phpsh,将一些内容放入变量中,匹配word。</p>
<pre><code>el@apollo:~/foo$ phpsh
php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'
php> echo preg_match('(\w+)', $content1);
1
php> echo preg_match('(\w+)', $content2);
1
php> echo preg_match('(\w+)', $content3);
0
</code></pre>
<p>preg_match方法使用PHP语言中的PCRE引擎来分析变量:<code>$content1</code>、<code>$content2</code>和<code>$content3</code>和<code>(\w)+</code>模式。</p>
<p>$content1和$content2至少包含一个单词,$content3不包含。</p>
<h2>用<code>(dart|fart)</code>匹配命令行中的许多文字单词</h2>
<pre><code>el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(dart|fart)', $gun1);
1
php> echo preg_match('(dart|fart)', $gun2);
1
php> echo preg_match('(dart|fart)', $gun3);
1
php> echo preg_match('(dart|fart)', $gun4);
0
</code></pre>
<p>变量gun1和gun2包含字符串dart或fart。gun4没有。然而,查找单词<code>fart</code>匹配<code>farty</code>可能是一个问题。要解决此问题,请在regex中强制使用单词边界。</p>
<h2>将命令行中的文字单词与单词边界匹配</h2>
<pre><code>el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0
php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0
</code></pre>
<p>所以它和前面的例子一样,只是内容中不存在单词边界为<code>\b</code>的单词<code>fart</code>。</p>