【问题标题】:regex is null in javascript but not in php正则表达式在 javascript 中为空,但在 php 中不是
【发布时间】:2014-01-23 15:51:42
【问题描述】:

我有这段文字

CREATE TABLE IF NOT EXISTS `arrivals` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `jobid` int(11) NOT NULL,
  `eta` int(32) NOT NULL,
  `keyword` varchar(255) NOT NULL,
  `url` varchar(255) NOT NULL,
  `searchengine` varchar(3) NOT NULL DEFAULT 'de' COMMENT 'Suchmaschine',
  `keywordid` int(11) NOT NULL,
  `urlid` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2040 ;

在 php 中这个正则表达式有效

preg_match_all ( "#(CREATE.*?);#s", $_POST["sql"], $matches );

在 javascript 中,这个正则表达式返回 null。为什么?

var result = textAreaText.match(/(CREATE.*?);/gm);

【问题讨论】:

  • 值是我提供的文本。
  • 使用不同的修饰符...期望相同的结果...s = DOTALL, m = MULTILINE
  • 也许我使用了不同的修饰符,因为 s 在 javascript 中不起作用,而 javascript 中的 g 与 php 中的 preg_match_all 相同?
  • g 很好。那是对的。但是 DOTALL 和 MULTILINE 不一样 ;)
  • 是的。我只是尝试了所有可用的修饰符,因为 s 不起作用。这就是它存在的原因。:)

标签: javascript php regex


【解决方案1】:

Javascript 没有 s 标志 (DOTALL),因此您可以使用:

var result = textAreaText.match(/(CREATE[\s\S]*?);/g);

DOT 匹配除​​换行符以外的任何字符,但使用 [\s\S] 使其也匹配任何字符和换行符。

此外,您实际上并不需要 m 修饰符,因为它用于在 MULTILINE 输入中使用锚点 ^ and $

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多