简体   繁体   中英

Regular expression to match “item” followed by two digits

I need a regular expression that would split strings like itemXY where X and Y are integer (item23) to be used in javascript.

I would like it to return the integers x and y.

Assuming that you are always going to have two digits, use this:

var item = "item24";
var result = item.match(/(\d)(\d)$/);
var digit1 = result[1];
var digit2 = result[2];

You don't need to bother the regex parser with this problem. If the first part of the string up to the number is always the same length, you can use slice() or substring() :

var str = "item23";

alert(str.slice(4));
//-> 23

This would be faster and less complicated than a regular expression. If you need the numbers to be separated, you can just split them:

var arr = str.slice(4).split();
//-> ["2", "3"]

If all you need are last digits then:

\d+$

will do the work. \\d+ means 1 or more digits, and $ means "at end". Then you can use result_string[0] and result_string[1] (of course you should check length):

var txt = "item25";
var result = txt.match(/\d+$/);
if (result != null)
    {
    var digits = result[0];
    alert(digits[0]);
    alert(digits[1]);
    }

You can also use regex groups like:

(\d)(\d)$

are you trying to extrac "23" to a variable?

here you are:

/^item([0-9]+)$/

will extract any number from itemXXXXXX returning that number.

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