简体   繁体   中英

Extract embedded number from string - JavaScript Regex

This deals with the general problem of extracting a signed number from a string that also contains hyphens.

Can someone please come up with the regex for the following:

 "item205"             => 205  
 "item-25              => -25  
 "item-name-25"        => -25  

Basically, we want to extract the number to the end of the string, including the sign, while ignoring hyphens elsewhere.

The following works for the first two but returns "-name-25" for the last:

var sampleString = "item-name-25";
sampleString.replace(/^(\d*)[^\-^0-9]*/, "")

Thanks!

You can use .match instead:

"item-12-34".match(/-?\d+$/);  // ["-34"]

The regexp says "possible hyphen, then one or more digits, then the end of the string".

Don't use replace . Instead, use match and write the regex for what you actually want (because that's a lot easier):

var regex = /-?\d+$/;
var match = "item-name-25".match(regex);
> ["-25"]
var number = match[0];

One thing about your regex though: in a character class you can only meaningfully use ^ once (right at the beginning) to mark it as a negated character class. It doesn't work for every single element individually. That means that your character class actually corresponds to "any character that is not a - , ^ or a digit.

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