简体   繁体   中英

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

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.

lastName, firstName # 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.

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

You can use capture groups in JS (from here )

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* will catch all the spaces.

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.

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

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