0

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

我想匹配,比如说,国际拼字游戏协会,但它可以是 ISA, Intl。Scrabble Assoc. 等。理想情况下,它们都将匹配 ISA。

可行吗?

4

1 回答 1

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.

如果你想玩它,这里是ideone 。

于 2013-01-24T04:17:19.253 回答