JavaScript正则表达式匹配是否需要重复代码

Does JavaScript regex matching require repeated code?

本文关键字:代码 是否 正则表达式 JavaScript      更新时间:2023-09-26

考虑Perl中的以下正则表达式代码片段:

if ($message =~ /^(.+) enters the race!$/)) {
    $racer = $1;
    print "Found $racer";
} else {
    print "Racer parsing error!";
}

我正在尝试将其移植到 JavaScript,这是我想出的:

if (message.match(/^.+ enters the race!$/)) {
    var racer = message.match(/^(.+) enters the race!$/)[1];
    console.log("Found " + racer);
} else {
    console.log("Racer parsing error!");
}

请注意正则表达式必须重复两次。这看起来很草率。更不用说它浪费了处理能力,因为它必须连续两次执行相同的正则表达式。有没有办法让这个代码片段看起来更干净?

您可以直接在 if 语句中检查正则表达式匹配。 这样的东西会起作用:

JavaScript

function check(message) {
    if (racer = message.match(/^(.+) enters the race!$/)) {
    console.log("Found " + racer[1]);
    } else {
    console.log("Racer parsing error!");
    }
}

check("blah enters the race!")
check("blah blah blah")

输出

发现废话
赛车手解析错误!

Perl 和 JS 中的代码之间存在一些差异:

  • JS没有字符串插值,所以你的代码必须有点冗长。
  • 没有类似$1全局变量,但您可以声明它在代码中使用。

您可以首先匹配并检查正则表达式是否匹配任何内容。

var message = "John enters the race!";
var m = message.match(/^(.+) enters the race!$/); // Match the string with a pattern
if (m) {                                          // Check if there is a match
    var racer = m[1];                             // Assign the captured substring to `racer`
    console.log("Found " + racer);              
} else {
    console.log("Racer parsing error!");
}

请注意,此处m是一个 Match 对象,其中包含:

  • m[0] - 整个匹配的文本
  • m[1] - 组 1(捕获组 1)的内容
  • m.index - 字符串中匹配项的从 0 开始的索引
  • m.input - 原始字符串

您可以将匹配结果存储在变量中:

var result = message.match(/^.+ enters the race!$/);
if (result) {
    var racer = result[1];
    console.log("Found " + racer);
} else {
    console.log("Racer parsing error!");
}

您可以运行一次匹配命令。如果失败,getmatches将为 null。如果成功,getmatches[1]将包含您的赛车手的名字

var rgx = /^(.+) enters the race!$/,
  message = window.prompt('Enter Message'),
  getmatches = message.match(rgx);
if (getmatches) {
  var racer = getmatches[1];
  console.log("Found " + racer);
} else {
  console.log("Racer parsing error!");
}

我认为您应该创建一个RegExp实例并使用test()exec()方法,如下所示:

var myRegExp = new RegExp('^(.+) enters the race!$');
var message = 'Someone enters the race!';
if (myRegExp.test(message)) {
  var racer = myRegExp.exec(message)[1];
  console.log('Found ' + racer);
} 
else {
  console.log('Racer parsing error!');
}

请注意正则表达式中 () 的用法。