正则表达式在javascript中产生不同的结果

时间:2022-02-17 12:10:21

Why does this regex return an entirely different result in javascript as compared to an on-line regex tester, found at http://www.gskinner.com/RegExr/

为什么这个正则表达式在javascript中返回完全不同的结果,与在线正则表达式测试器相比,可在http://www.gskinner.com/RegExr/找到

var patt = new RegExp(/\D([0-9]*)/g);
"/144444455".match(patt);

The return in the console is:

控制台中的返回是:

["/144444455"]

While it does return the correct group in the regexr tester.

虽然它确实在regexr测试器中返回正确的组。

All I'm trying to do is extract the first amount inside a piece of text. Regardless if that text starts with a "/" or has a bunch of other useless information.

我要做的就是在一段文字中提取第一笔金额。无论该文本以“/”开头还是有一堆其他无用的信息。

1 个解决方案

#1


3  

The regex does exactly what you tell it to:

正则表达式正是你告诉它的:

  • \D matches a non-digit (in this case /)
  • \ D匹配非数字(在本例中为/)
  • [0-9]* matches a string of digits (144444455)
  • [0-9] *匹配一串数字(144444455)

You will need to access the content of the first capturing group:

您需要访问第一个捕获组的内容:

var match = patt.exec(subject);
if (match != null) {
    result = match[1];
}

Or simply drop the \D entirely - I'm not sure why you think you need it in the first place...

或者简单地完全放弃\ D - 我不确定为什么你认为你首先需要它...

Then, you should probably remove the /g modifier if you only want to match the first number, not all numbers in your text. So,

然后,如果您只想匹配文本中的第一个数字而不是所有数字,则应该删除/ g修饰符。所以,

result = subject.match(/\d+/);

should work just as well.

也应该工作。

#1


3  

The regex does exactly what you tell it to:

正则表达式正是你告诉它的:

  • \D matches a non-digit (in this case /)
  • \ D匹配非数字(在本例中为/)
  • [0-9]* matches a string of digits (144444455)
  • [0-9] *匹配一串数字(144444455)

You will need to access the content of the first capturing group:

您需要访问第一个捕获组的内容:

var match = patt.exec(subject);
if (match != null) {
    result = match[1];
}

Or simply drop the \D entirely - I'm not sure why you think you need it in the first place...

或者简单地完全放弃\ D - 我不确定为什么你认为你首先需要它...

Then, you should probably remove the /g modifier if you only want to match the first number, not all numbers in your text. So,

然后,如果您只想匹配文本中的第一个数字而不是所有数字,则应该删除/ g修饰符。所以,

result = subject.match(/\d+/);

should work just as well.

也应该工作。