字符串首字母匹配正则表达式

时间:2013-01-24 03:39:17

标签: regex

正则表达式是否可以匹配字符串中单词的首字母?例如:

我想匹配国际拼字游戏协会,但它可以作为ISA,Intl。 Scrabble Assoc。等。理想情况下,他们都将匹配ISA。

可行?

1 个答案:

答案 0 :(得分:1)

如果你问是否有一种方法可以在本地进行,只有正则表达式,那么不,没有办法做到这一点。你必须拆分你的字符串并提取首字母(可能使用正则表达式),然后从中构造一个新的正则表达式。因此,解决方案取决于您的实现,当然,这是PHP中的一个示例:

<?php
    $str = "International Scrabble Assocation";
    preg_match_all('/\b(\w)\w*\b/i', $str, $matches);
    $regex = '/\b' . implode('\S*\s*', array_map(strtoupper, $matches[1])) . '\S*\b/';
    $tests = array('Intl. Scrabble Assoc.',
                   'Intl Scrabble Assoc',
                   'I.S.A',
                   'ISA',
                   'Intl. SA', 
                   'intl scrabble assoc',
                   'i.s.a.',
                   'isa',
                   'lisa',
                   'LISA',
                   'LI. S. A.');
    echo "The generated regex is $regex.\n\n";
    foreach ($tests as $test)
    {
        echo "Does '$test' match? " . (preg_match($regex, $test) ? 'Yes' : 'No') . ".\n";
    }
?>

输出:

The generated regex is /\bI\S*\s*S\S*\s*A\S*\b/.
Does 'Intl. Scrabble Assoc.' match? Yes.
Does 'Intl Scrabble Assoc' match? Yes.
Does 'I.S.A' match? Yes.
Does 'ISA' match? Yes.
Does 'Intl. SA' match? Yes.
Does 'intl scrabble assoc' match? No.
Does 'i.s.a.' match? No.
Does 'isa' match? No.
Does 'lisa' match? No.
Does 'LISA' match? No.
Does 'LI. S. A.' match? No.

Here's the ideone如果你想玩它。