虽然丑陋且难以阅读,但我会创建一个函数来为每个单词创建正则表达式。例如,如果它是 PHP,我会将其公式化如下:
function rx_from_word($word='',$escapeNeeded=true) {
$rx = ''; $i = strlen($word);
while (--$i > -1) {
if ($escapeNeeded && strpos('|/{}[]().*\\+^$',$word{$i}) !== false) $char = '\\'.$word{$i};
// I'm not sure if I missed any special character above.
else $char = $word{$i};
if ($i > 0) $rx = '(' . $char . $rx . ')?';
else $rx = $char . $rx;
}
return $rx;
}
function rx_from_words($words=array(),$matchFull=false) {
$rx = $matchFull ? '^' : '';
foreach ($words as $word) $rx .= rx_from_word($word) . '|';
return substr($rx,0,-1) . ($matchFull ? '$' : '');
}
$words = array('horizontal','vertical','$10');
$rx = rx_from_words($words,1);
echo "<pre>$rx</pre>";
这将输出
^h(o(r(i(z(o(n(t(a(l)?)?)?)?)?)?)?)?)?|v(e(r(t(i(c (a(l)?)?)?)?)?)?)?|\$(1(0)?)?$