简体   繁体   English

如何使用星号匹配Javascript中的多数字正则表达式

[英]How to Match Multi-Digit Regex In Javascript Using the Star

I am trying to extract a multi-digit number which is preceeded by a non-digit from a string in javascript, but having trouble. 我正在尝试从JavaScript中的字符串中提取非数字开头的多位数,但是遇到了麻烦。 For example, I want to get the "32" out of "B32 is the floor". 例如,我要从“ B32是地板”中获取“ 32”。

var str = "B23 is the floor."
var num = str.match(/\d*/);
$("#result").append(Object.prototype.toString.call(num) + ', ');
$("#result").append(Object.prototype.toString.call(num[0]) + ', ');
$("#result").append(num[0] + ', ');
$("#result").append(num[0].length);

Returns: 返回:

Result:[object Array], [object String], , 0

num[0] seems to be an empty string. num [0]似乎是一个空字符串。

For some reason the regext /\\d*/ does not work the way it is supposed to. 由于某种原因,正则表达式/ \\ d * /无法正常运行。 I have tried /(\\d) /, /(\\d)*/, /[0-9] /, and some other reasonable and unreasonable things, but it just doesn't seem to work. 我已经尝试过/(\\ d) /,/(\\ d)* /,/ [0-9] /和其他一些合理且不合理的事情,但似乎不起作用。

Here is my jsFiddle if you want to take a look: http://jsfiddle.net/PLYHF/3/ 如果您想看一下,这是我的jsFiddle: http : //jsfiddle.net/PLYHF/3/

The problem is that the regex parser is "lazy". 问题在于正则表达式解析器是“惰性”的。 It sees that your regex is perfectly fine with "nothing" (since * means 0 or more), so anything will pass. 它会看到您的正则表达式完全正确,并且“什么都没有”(因为*表示0或更大),所以任何东西都会通过。

Instead, try /\\d+/ . 而是尝试/\\d+/ This will force there to be at least one digit. 这将强制至少有一位数字。

What you'll want to do is match for /^0-9/, and then get the second value ( Array[1] ) from the returned array. 您要做的是匹配/ ^ 0-9 /,然后从返回的数组中获取第二个值( Array[1] )。 That will contain what's captured by the first group. 这将包含第一组捕获的内容。 It would end up looking like this: 最终看起来像这样:

var str = "B23 is the floor."
var num = str.match(/[^0-9\s]([0-9]+)/);
$('#result').append(num[1]);

demo 演示

parseInt(/[A-Z]+([0-9]+)/.exec('B23 is the floor.')[1]); // 23

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

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