如何检测字符串中的名称、数字和注释(可选)


How to detect a name, a number and comment (optional) in a string with PHP?

我遇到了一个麻烦,我有以下几行:

John Smith
John Smith +1
John Smith (drink)
John Smith              (    drink      )         
John Smith, drink
John Smith   ,    drink
John Smith   +1   ,    drink
John Smith +1 (drink)
John Smith +1, drink
John Smith +1 drink

我需要做的是将它们放入一个数组中,比如

'array' => 
    'name' => 'John Smith',
    'plus' => '',
    'comment' => ''
,
'array' =>
    'name' => 'John Smith',
    'plus' => '+1',
    'comment' => ''
,
'array' => 
    'name' => 'John Smith',
    'plus' => '',
    'comment' => 'drink'

等等…看起来我需要一些谷歌级别的正则表达式。到目前为止,我用'nforeach爆破了整个。txt文件,然后用space爆破,但后来我发现自己陷入了一团糟的境地。如果有人有更好的主意,我会毫不犹豫地告诉你。任何帮助都是感激的。我说的任何,是指任何一种。

让我为您提供一个非常脆弱的解决方案,它适用于您的示例字符串:

^ *+([A-Za-z ]*[A-Za-z]) *+('+'d+)?+ *+(?|,?+ *+'( *+(.*'S) *') *|,?+ *+(.*'S) *)?$

Name将在捕获组1中。号码(包括签名)将在捕获组2。注释将在捕获组3中

目前的假设是name只能包含空格和英文字母。

另一个假设是只有空格(ASCII 32)被识别为空格字符。

Demo(请忽略标志,它们仅用于演示目的)

另一个用于您的示例

道路的脆弱正则表达式
$lines = array
(
"John Smith",
"John Smith +1",
"John Smith (drink)",
"John Smith              (    drink      )",
"John Smith, drink",
"John Smith   ,    drink",
"John Smith   +1   ,    drink",
"John Smith +1 (drink)",
"John Smith +1, drink",
"John Smith +1 drink"
);
foreach($lines as $line)
{
    preg_match('/^(?<name>'w+(?:'s+'w+)?)(?:['s,]+(?<plus>'+'d+))?(?:['s,'(]+(?<comment>'w+)['s')]*)?$/', $line, $matches);
    var_dump($matches);
}