これは、正規表現を xml/html などの解析に使用すべきではないという警告で機能します。
単純なサンプルをキャプチャしてから、コールバックでサブプロセスする方が常に簡単です。
この場合、([alphabet"*`,]+) をキャプチャし、不要な文字を取り除き、比較を行います。
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";
}
?>