這將與正則表達式不應該被用來解析XML/HTML等的告誡工作..
它總是更容易捕捉簡單樣本,然後子進程它們的回調。
在這種情況下,捕獲([字母「*`,] +),然後去掉不需要的字符,然後做一個比較。
一個Perl示例,其概念與Perl/PHP/C#等相同。 ..
$sample = '
<hw>Al"pha*bet</hw>
<hw>Al"pha*be`t</hw>
<hw>alphabet</hw>
<hw>al*pha*bet</hw>
<hw>al"pha"b"et</hw>
';
$specialword = 'alphabet';
$uc_specialword = uc($specialword);
while ($sample =~ m{<([A-Za-z_:][\w:.-]*)(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s*(?<!/)>([$specialword"*`,]+)</\1\s*>}isg)
{
($matchstr, $checkstr) = ($&, $2);
$checkstr =~ s/["*`,]//g;
if (uc($checkstr) eq $uc_specialword) {
print "Found '$checkstr' in '$matchstr'\n";
}
}
擴展正則表達式:
m{ # Regex delim
< # Open tag
([A-Za-z_:][\w:.-]*) # Capture 1, the tag name
(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s* # optional attr/val pairs
(?<!/)
>
([alphabet"*`,]+) # Capture 2, class of special characters allowed, 'alphabet' plus "*`,
</\1\s*> # Close tag, backref to tag name (group 1)
}xisg # Regex delim. Options: expanded, case insensitive, single line, global
輸出:
Found 'Alphabet' in '<hw>Al"pha*bet</hw>'
Found 'Alphabet' in '<hw>Al"pha*be`t</hw>'
Found 'alphabet' in '<hw>alphabet</hw>'
Found 'alphabet' in '<hw>al*pha*bet</hw>'
Found 'alphabet' in '<hw>al"pha"b"et</hw>'
PHP示例的
使用preg_match()
可以在這裏http://www.ideone.com/8EBpx
<?php
$sample = '
<hw>Al"pha*bet</hw>
<hw>Al"pha*be`t</hw>
<hw>alphabet</hw>
<hw>al*pha*bet</hw>
<hw>al"pha"b"et</hw>
';
$specialword = 'alphabet';
$uc_specialword = strtoupper($specialword);
$regex = '~<([A-Za-z_:][\w:.-]*)(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s*(?<!/)>([' . $specialword. '"*`,]+)</\1\s*>~xis';
$pos = 0;
while (preg_match($regex, $sample, $matches, PREG_OFFSET_CAPTURE, $pos))
{
$matchstr = $matches[0][0];
$checkstr = $matches[2][0];
$checkstr = preg_replace('/[" * `,]/', "", $checkstr);
if (strtoupper($checkstr) == $uc_specialword)
print "Found '$checkstr' in '$matchstr'\n";
$pos = $matches[0][1] + strlen($matchstr);
}
?>
使用preg_match_all()
發現可以在這裏找到http://www.ideone.com/C6HeT
<?php
$sample = '
<hw>Al"pha*bet</hw>
<hw>Al"pha*be`t</hw>
<hw>alphabet</hw>
<hw>al*pha*bet</hw>
<hw>al"pha"b"et</hw>
';
$specialword = 'alphabet';
$uc_specialword = strtoupper($specialword);
$regex = '~<([A-Za-z_:][\w:.-]*)(?:\s+(?:".*?"|\'.*?\'|[^>]*?)+)?\s*(?<!/)>([' . $specialword. '"*`,]+)</\1\s*>~xis';
preg_match_all($regex, $sample, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
{
$matchstr = $match[0];
$checkstr = $match[2];
$checkstr = preg_replace('/[" * `,]/', "", $checkstr);
if (strtoupper($checkstr) == $uc_specialword)
print "Found '$checkstr' in '$matchstr'\n";
}
?>
你心裏有一個特定的語言?請注意,我的第一個想法是拉動帶標籤的子串,消除這些字符然後匹配,但根據您的語言或數據集可能不理想。 – 2011-12-27 15:13:49
是的..最好的方式去這種取決於什麼語言,以及如何獲取示例數據開始。例如,如果您使用的是XML解析器類(例如php),那麼您可以使用預製函數輕鬆抓取標籤。但即使使用純正則表達式直接抓取原始內容,它仍然是「更清潔」的,去除特殊字符,然後與「字母」進行比較...特別是因爲我有一個偷偷摸摸的「字母」只是一個例子,你會將這個應用到任何單詞... – 2011-12-27 15:33:31
你會匹配的語言字符串?你想匹配什麼:單詞,行,標籤(含內容),還是像上面這樣的完整塊? – Qtax 2011-12-27 15:40:49