Php 将带注释的多行(freespace)正则表达式传递给preg_匹配

Php 将带注释的多行(freespace)正则表达式传递给preg_匹配,php,regex,Php,Regex,我有一个正则表达式,它最终会有点长,如果能跨多行阅读,会更容易阅读 我试过这个,但它吐出来了 preg_match( '^J[0-9]{7}:\s+ (.*?) #Extract the Transaction Start Date msg \s+J[0-9]{7}:\s+Project\sname:\s+ (.*?) #Extract the Project Name \s+J[0-9]{7}:\s+Job

我有一个正则表达式,它最终会有点长,如果能跨多行阅读,会更容易阅读

我试过这个,但它吐出来了

preg_match(
    '^J[0-9]{7}:\s+
    (.*?)             #Extract the Transaction Start Date msg
    \s+J[0-9]{7}:\s+Project\sname:\s+
    (.*?)             #Extract the Project Name
    \s+J[0-9]{7}:\s+Job\sname:\s+
    (.*?)             #Extract the Job Name
    \s+J[0-9]{7}:\s+',
    $this->getResultVar('FullMessage'),
    $atmp
);

是否有方法将上述形式的正则表达式传递给preg_match?

您可以使用扩展语法:

preg_match("/
    test
/x", $foo, $bar);
好的,这里有一个解决方案:

preg_match(
                '/(?x)^J[0-9]{7}:\s+
                (.*?)             #Extract the Transaction Start Date msg
                \s+J[0-9]{7}:\s+Project\sname:\s+
                (.*?)             #Extract the Project Name
                \s+J[0-9]{7}:\s+Job\sname:\s+
                (.*?)             #Extract the Job Name
                \s+J[0-9]{7}:\s+/'
                , $this->getResultVar('FullMessage'), $atmp);
开头的键是(?x),这使得空白变得无关紧要,并允许注释

同样重要的是,在开始和结束引号以及正则表达式的开始和结束之间没有空格

我的第一次尝试出现了以下错误:

preg_match('
                /(?x)^J[0-9]{7}:\s+
                (.*?)             #Extract the Transaction Start Date msg
                \s+J[0-9]{7}:\s+Project\sname:\s+
                (.*?)             #Extract the Project Name
                \s+J[0-9]{7}:\s+Job\sname:\s+
                (.*?)             #Extract the Job Name
                \s+J[0-9]{7}:\s+/
           ', $this->getResultVar('FullMessage'), $atmp);

在PHP中,注释语法如下所示: (?# Your comment here) 有关更多信息,请参阅

您也可以使用PCRE_EXTENDED(或“x”),如Mark在其示例中所示。

  • 您应该添加分隔符:正则表达式的第一个字符将用于指示模式的结束
  • 您应该添加“x”标志。这与将(?x)放在开头的结果相同,但更易于阅读

是的,您可以添加
/x

此修改器将启用“附加” PCRE的功能,即 与Perl不兼容。有反斜杠吗 在后面跟着一个 没有特殊意义的字母 导致错误,因此保留这些 用于未来扩展的组合。通过 默认情况下,如在Perl中,是反斜杠 然后是一封没有特别说明的信 意义被视为字面意义。那里 目前没有其他功能 由该修改器控制

对于您的示例,请尝试以下方法:

preg_match('/
              ^J[0-9]{7}:\s+
              (.*?)             #Extract the Transaction Start Date msg
              \s+J[0-9]{7}:\s+Project\sname:\s+
              (.*?)             #Extract the Project Name
              \s+J[0-9]{7}:\s+Job\sname:\s+
              (.*?)             #Extract the Job Name
              \s+J[0-9]{7}:\s+
            /x', $this->getResultVar('FullMessage'), $atmp);

有趣。用a+分隔的标签在问题中单独显示,但在右侧显示组合的AND标签。
preg_match('/
              ^J[0-9]{7}:\s+
              (.*?)             #Extract the Transaction Start Date msg
              \s+J[0-9]{7}:\s+Project\sname:\s+
              (.*?)             #Extract the Project Name
              \s+J[0-9]{7}:\s+Job\sname:\s+
              (.*?)             #Extract the Job Name
              \s+J[0-9]{7}:\s+
            /x', $this->getResultVar('FullMessage'), $atmp);