![](/img/trans.png)
[英]A while loop to add the digits of a multi-digit number together? (Javascript)
[英]How to Match Multi-Digit Regex In Javascript Using the Star
我正在尝试从JavaScript中的字符串中提取非数字开头的多位数,但是遇到了麻烦。 例如,我要从“ 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);
返回:
Result:[object Array], [object String], , 0
num [0]似乎是一个空字符串。
由于某种原因,正则表达式/ \\ d * /无法正常运行。 我已经尝试过/(\\ d) /,/(\\ d)* /,/ [0-9] /和其他一些合理且不合理的事情,但似乎不起作用。
如果您想看一下,这是我的jsFiddle: http : //jsfiddle.net/PLYHF/3/
问题在于正则表达式解析器是“惰性”的。 它会看到您的正则表达式完全正确,并且“什么都没有”(因为*
表示0或更大),所以任何东西都会通过。
而是尝试/\\d+/
。 这将强制至少有一位数字。
您要做的是匹配/ ^ 0-9 /,然后从返回的数组中获取第二个值( Array[1]
)。 这将包含第一组捕获的内容。 最终看起来像这样:
var str = "B23 is the floor."
var num = str.match(/[^0-9\s]([0-9]+)/);
$('#result').append(num[1]);
parseInt(/[A-Z]+([0-9]+)/.exec('B23 is the floor.')[1]); // 23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.