匹配字符串中的格式和 return 标记

match format and return tokens from a string

我正在尝试在 PHP 中使用正则表达式解析大文本。我知道行格式,下面使用 sprintf 格式显示,以便于解释。

所以一行包含一些已知的单词(或括号)。我想知道匹配的格式(在示例中我打印了格式数组键)并从行中提取了一些相关数据。

我试过 '/(?<=new message from )(.*)(?=[)(.*)(?=:)(.*)(?=:)(.*)(?=:)(.*)(?=])/' 等正则表达式格式,但除了匹配之外,我无法从行中提取正确的数据。

$input = [
    'new message from Bob [22:105:3905:534]',
    'user Dylan posted a question in section General',
    'new message from Mary(gold) [19504:8728:18524:78941]'
];

$formats = [
    'new message from %s [%d:%d:%d:%d]', // this would actually be something like '/(?<=new message from )(.*)(?=[)(.*)(?=:)(.*)(?=:)(.*)(?=:)(.*)(?=])/'
    'user %s posted a question in section %s',
    'new message from %s(%s) [%d:%d:%d:%d]',
];

foreach ($input as $line) {
    foreach ($formats as $key => $format) {
        $data = [];
        if (preg_match($format, $line, $data)) {
            echo 'format: ' . $key . ', data: ' . var_export($data, true) . "\n";
            continue;
        }
    }
}

// should yield:
// format: 0, data: array ( 0 => 'Bob', 1 => 22, 2 => 105, 3 => 3905, 4 => 534, )
// format: 1, data: array ( 0 => 'Dylan', 1 => 'General', )
// format: 2, data: array ( 0 => 'Mary', 1 => 'gold', 2 => 19504, 3 => 8728, 4 => 18524, 5 => 78941, )

我需要:

  1. 一种高效的正则表达式格式,用于匹配一行,使用多个通配符
  2. 一种提取通配符的方法,当正则表达式格式匹配一行时(也许 preg_match 不是在这种情况下使用的最佳正则表达式 php 函数)

我可以使用字符串函数(strpos 和 substr)来做到这一点,但代码看起来很糟糕..

谢谢!

稍微调整一下图案。请看下面的代码。

<?php

$input = [
    'new message from Bob [22:105:3905:534]',
    'user Dylan posted a question in section General with space',
    'new message from Mary(gold) [19504:8728:18524:78941]'
];

$formats = [
    '/new message from (\w+) \[(\d+):(\d+):(\d+):(\d+)\]/', // this would actually be something like '/(?<=new message from )(.*)(?=[)(.*)(?=:)(.*)(?=:)(.*)(?=:)(.*)(?=])/'
    '/user (\w+) posted a question in section ([\w ]+)/',
    '/new message from (\w+)\((\w+)\) \[(\d+):(\d+):(\d+):(\d+)\]/',
];

foreach ($input as $line) {
    foreach ($formats as $key => $format) {
        $data = [];
        if (preg_match($format, $line, $data)) {                            
            array_shift($data); 
            echo 'format: ' . $key . ', data: ' . var_export($data, true) . "\n";
            continue;
        }
    }
}

// should yield:
// format: 0, data: array ( 0 => 'Bob', 1 => 22, 2 => 105, 3 => 3905, 4 => 534, )
// format: 1, data: array ( 0 => 'Dylan', 1 => 'General', )
// format: 2, data: array ( 0 => 'Mary', 1 => 'gold', 2 => 19504, 3 => 8728, 4 => 18524, 5 => 78941, )

https://3v4l.org/NBgaT

编辑:我添加了一个 array_shift() 来删除与完整模式匹配的文本。