简体   繁体   English

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

[英]Regex to match full name with comma or space

I'm working with CommonMark and I've created a '@mention' parser that will return a link when an @mention is found. 我正在使用CommonMark,并且创建了一个'@mention'解析器,当找到@mention时它将返回链接。 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): 但是,这似乎捕获了错误的名称,并链接了其他名称的开头(请参见下文):

在此处输入图片说明

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) (一个名称最多只能包含2个单词,最多3个单词)

  • 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: 这是match方法背后的CommonMark代码:

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;
}

As per your new rules, match a name that has 2 or 3 words and should be separated by spaces ( ) or commas (,) 根据您的新规则,匹配一个包含2个或3个单词的名称,并用空格()或逗号(,)分隔

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

Regex 101 正则表达式101

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 和工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM