简体   繁体   English

正则表达式匹配“ item”,后跟两位数字

[英]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. 我需要一个正则表达式,该表达式将拆分像itemXY这样的字符串,其中X和Y是整数(item23),以便在javascript中使用。

I would like it to return the integers x and y. 我希望它返回整数x和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() : 如果直到数字的字符串的第一部分始终是相同长度,则可以使用slice()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". \\d+表示1个或多个数字,而$表示“末尾”。 Then you can use result_string[0] and result_string[1] (of course you should check length): 然后,您可以使用result_string[0]result_string[1] (当然,您应该检查长度):

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? 您是否正在尝试将“ 23”提取为变量?

here you are: 这个给你:

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

will extract any number from itemXXXXXX returning that number. 将从itemXXXXXX中提取任何数字,并返回该数字。

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

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