简体   繁体   English

Javascript regexp exec不起作用

[英]Javascript regexp exec doesn't work

Recently I posted a question about time format conversion via regular expressions in JS. 最近我通过JS中的正则表达式发布了一个关于时间格式转换的问题

Now I modified the code a bit. 现在我修改了一下代码。

function getHours(value) {
  if (value == 0)
    return 0;
  var re = new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");
  var myArray = re.exec(value);
  var hours = 0;
  var minutes = 0;
  if (myArray != null) {
    if (myArray[2] != null) {
      hours = myArray[2];
    }
    if (myArray[5] != null) {
      minutes = myArray[5];
    }
  }
  return Number(hours) + Number(minutes) / 60;
}

The problem is that it returns a null value in myArray . 问题是它在myArray返回一个null值。

As I'm new to JS, I couldn't solve this problem. 由于我是JS的新手,我无法解决这个问题。 What am I doing wrong? 我究竟做错了什么?

The problem is here 问题出在这里

new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");

When you create a new Regular Expression through the constructor, you provide strings. 通过构造函数创建新的正则表达式时,您将提供字符串。 In string literals, the backslash character ( \\ ) means 'escape the next character'. 在字符串文字中,反斜杠字符( \\ )表示“转义下一个字符”。

You have to escape those backslashes, so they won't escape their subsequent character. 你必须逃避那些反斜杠,所以他们不会逃避他们后来的角色。 So the correct version is: 所以正确的版本是:

new RegExp("^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$", "g");

See this article on values, variables, and literals from MDN for more information on escaping characters in JavaScript. 有关在JavaScript中转义字符的更多信息,请参阅有关MDN中的值,变量和文字的文章

Problem is in this line: 问题在于这一行:

var re = new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");

Pls understand that RegExp class takes a String as argument to construct and you need to double escape \\d and \\s to be correctly interpreted by RegEx engine so \\d should become \\\\d and \\s should become \\\\s in your regex String like this: 请理解, RegExp class将String作为参数进行构造,并且您需要双重转义\\d\\s才能被RegEx引擎正确解释,因此\\d应该成为\\\\d并且\\s应该在正则表达式字符串中成为\\\\s像这样:

var re = new RegExp("^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$", "g");

Note that you can also do: 请注意,您还可以这样做:

var re = /^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g;

I changed exec call like this: var myArray = (/^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$/g).exec(value); 我改变了这样的exec调用: var myArray = (/^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$/g).exec(value);

And it worked! 它奏效了! Can anyone explain the difference? 有人可以解释这个区别吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM