2013-01-24 179 views
0

正则表达式匹配字符串中单词的首字母缩写吗?例如:字符串首字母匹配正则表达式

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

可以吗?

回答

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

+0

是的,问题是“仅限正则表达式”。谢谢你的回答。 – SxN

+0

其实,acheong,你激励了我:这是一种方法:\ bI \ w {0,12}。? ?s \ W {0,7}? ?A当然,它将与Integrated Star Aloha相匹配,但在我的情况下,它是可以的。再次感谢。 – SxN

相关问题