简体   繁体   中英

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. For example, I want to get the "32" out of "B32 is the floor".

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.

For some reason the regext /\\d*/ does not work the way it is supposed to. I have tried /(\\d) /, /(\\d)*/, /[0-9] /, and some other reasonable and unreasonable things, but it just doesn't seem to work.

Here is my jsFiddle if you want to take a look: 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.

Instead, try /\\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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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