PHP Regex匹配以大写字母开头的那些

时间:2011-08-18 04:09:48

标签: php regex

这听起来很简单,但我无法弄明白,请帮助我。

所以...我有以下数据的文件:

Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..

我只需匹配以“名字:”开头的整个部分......不是“姓氏:”......

以下是我现在正在使用的内容:

/Name(:)(.*)/i

它会匹配两者但我需要名字:...

请不要建议任何其他寻找方式,请帮我解决正则表达式的问题。

3 个答案:

答案 0 :(得分:0)

不使用i修饰符,这会使正则表达式不区分大小写。

和/或,添加一些单词边界:

/\bName(:) (.*)\b/

答案 1 :(得分:0)

^字符将匹配行的开头:

/^Name(:)(.*)/

注意,我删除了i修饰符,这会使您的搜索不区分大小写。

样品:

% cat ./test.php 
#!/usr/bin/env php
<?php

$regex = '/^Name(:)(.*)/';

$data = <<<EOD
Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..
EOD;

foreach (explode("\n", $data, -1) as $line)
{
    if (preg_match($regex, $line, $matches))
    {
        printf("Found %s\n", $matches[2]);
    }
}


?>

% ./test.php
Found  Santi
Found  Rob

答案 2 :(得分:0)

/\b^(Name):\s[A-Z]+\s\b/   

使用\s来处理空格。

相关问题