duandu9260
2017-05-04 18:26
浏览 236
已采纳

正则表达式匹配全名与逗号或空格

I'm working with CommonMark and I've created a '@mention' parser that will return a link when an @mention is found. However, I'm tweaking it to link full names instead of usernames. Here's what I currently have:

$cursor->match('/^\w+,(.*)\s/');

However, this seems to capture the name incorrectly, and links the start of the other name (see below):

enter image description here

Does anyone have any ideas what I could change to match an entire name separated with a comma and/or space? I'm awful at writing regex.

Thanks for any help in advance!

Edit:

Here's what should match:

(A name can only be 2 words minimum and 3 words maximum)

  • Bauman, Steve
  • Steve Bauman
  • Doe, Mary Sue
  • Mary Sue Doe

A last name with a comma will only be one word.

What should not match:

  • Steve
  • Bauman
  • Mary
  • Doe

The regex needs to match an entire name, not single names.

This is the CommonMark code behind the match method:

if (!preg_match($regex, $subject, $matches, PREG_OFFSET_CAPTURE)) {
    return;
}

This results to:

if (!preg_match('/^\w+,(.*)\s/', "Bauman, Steve", $matches, PREG_OFFSET_CAPTURE)) {
    return;
}

图片转代码服务由CSDN问答提供 功能建议

我正在使用CommonMark,我创建了一个'@mention'解析器,它将返回一个链接 @mention被找到了。 但是,我正在调整它以链接全名而不是用户名。 这是我目前所拥有的:

  $ cursor-> match('/ ^ \ w +,(。*)\ s /'); 
  <  / pre> 
 
 

然而,这似乎错误地捕获了名称,并链接了另一个名称的开头(见下文):

是否有人有任何想法可以更改以匹配用逗号和/或空格分隔的整个名称? 我很难写正则表达式。

感谢您提前提供任何帮助!

编辑

以下是应该匹配的内容:

(名称最少只能为2个字,最多3个字)

  • Bauman,Steve
  • Steve Bauman
  • Doe,Mary Sue
  • Mary Sue Doe

    带逗号的姓氏为一个单词。

    不应匹配的内容:

    • 史蒂夫
    • 鲍曼
    • 玛丽
    • Doe的

      正则表达式需要匹配整个名称,而不是单个名称。

      这是 match 方法背后的CommonMark代码:< / p>

        if(!preg_match($ regex,$ subject,$ matches,PREG_OFFSET_CAPTURE)){
       return; 
      } 
         
        
       

      结果为:

        if(!preg_match('/ ^ \ w +,(。*)\ s /',“Bauman,Steve”,$ 匹配,PREG_OFFSET_CAPTURE)){
       return; 
      } 
         
       
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doupang5433 2017-05-04 19:26
    已采纳

    As per your new rules, match a name that has 2 or 3 words and should be separated by spaces ( ) or commas (,)

    /\w+([, ]+\w+){1,2}/
    

    Regex 101

    点赞 打赏 评论
  • drbouzlxb92333332 2017-05-04 18:35

    Here you go

    <?php
    $string = <<<EOS
    something @name, bla bla bla @name.surname something else
    Lorem ipsum @o'brien 
    EOS;
    
    $matches = [];
    preg_match_all('/@[^\s,]+/', $string, $matches);
    var_dump($matches);
    

    and working demo

    点赞 打赏 评论

相关推荐 更多相似问题