简体   繁体   English

Javascript RegEx:在符号后获取1或2位数字(不包括该符号)

[英]Javascript RegEx: Get 1 or 2 digits after a symbol (Excluding that symbol)

Thanks in advance for taking a look at this. 在此先感谢您看一下。 I'm having some difficulty extracting something to create a sports project. 我在提取某些内容以创建体育项目时遇到了一些困难。 I've got the following situation: 我有以下情况:

lastName, firstName #33 6 姓氏,名字#33 6

Which works fine with the following: 可以在以下情况下正常工作:

var number = $(this).text().match(/\d{1,2}/);

But, if I use it for the following (missing the number) than it's grabbing the 6, because obviously I am searching for one or two digits. 但是,如果我将它用于以下内容(缺少数字)而不是抓住6,因为显然我正在搜索一两位数字。

lastName, firstName # 6 姓氏,名字#6

Basically what I'm trying to do is pull in a one or two digit number after the number sign (if there is one) but ignore anything that comes after it and before it (# included). 基本上,我想做的是在数字符号后(如果有)输入一个或两个数字,但是忽略它之后和它之前(包括#)的所有内容。 I'm not extremely handy with RegEx so hopefully one of you are able to understand what I mean by this. 我对RegEx不太方便,因此希望你们中的一个能够理解我的意思。

Try: #(\\d{1,2}) 试试: #(\\d{1,2})

You can use capture groups in JS (from here ) 您可以在JS中使用捕获组(从此处开始

var myString = "something format_abc";
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
alert(match[1]);

To allow spaces between # and number: #\\s*(\\d{1,2}) 要在#和数字之间留空格: #\\s*(\\d{1,2})

\\s* will catch all the spaces. \\s*将捕获所有空格。

There seems to be no leading 0 possible, so I added that restriction and also the number has to be followed by a whitespace or it has to be a the end. 似乎没有前导0的可能,因此我添加了该限制,并且该数字还必须后面跟一个空格,否则必须是一个结尾。

var re = /#\s*([1-9][0-9]?)(?:\s|$)/;
var matches = [];
var str = '...';
while ((match = re.exec(str)) != null) {
    matches.push(match[1]);
}

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

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