简体   繁体   中英

How do I get percentage values from a string with a regular expression?

How can I get the percentage values from this string but without the percent sign?

I have this string and I'd like to get the %s out without the percent sign. I have it mostly working except the percent sign comes along like this:

"asfd %1.3344 %1.2323 % asdf %".match(/%[0-9.]*/g)

Result: ["%1.3344", "%1.2323", "%", "%" ]

I'd like the result to be [ 1.3344, 1.2323]

I tried doing it with a regex look ahead, but I get ["", "", "", ""]. This was my attempt:

"asfd %1.3344 %1.2323 % asdf %".match(/(?=%)[0-9.]*/g)

result: ["", "", "", "" ]

"asfd %1.3344 %1.2323 % asdf %".match(/%[0-9.]+/g).map( function (item) { return item.substr(1); })

The usual solution here is to put what you want in a group and use exec in a loop:

var re = /%(\d+(?:\.\d*)?)/g;
var percentages = [];
var m;

while(m = re.exec(str)) {
    percentages.push(+m[1]);
}

Note the more restrictive regular expression, too: at least one digit, followed by an optional decimal separator followed by any number of digits.

I believe that this should also work.

JavaScript:

var str = "asfd %1.3344 %1.2323 % asdf %",
    arr = [];

str.replace(/%(\d+(?:\.\d*)?)/g, function (a, b) {
    arr.push(b);
});

console.log(arr);

jsFiddle

Hey I also checked and found this solution:

var str="asfd %1.3344 %1.2323 % asdf %";
var patt=/%([0-9\.]+)/g;
var result;
while(null != (result = patt.exec(str))){
    document.write(result[1] + '<br />');
} 

The following regex seams to work pretty well in this case without loop.

var str = "asfd %1.3344 %1.2323 % asdf %", resultsArray;
resultsArray = str.replace(/(^[^%]+)|[^\d .]|( (?!%\d))/g,'').split(' ');

Split String's method will return you an array

If there are some other kind of pattern you can encounter in your input (like if 2 dots can appear one after the other "asfd %1.. %1.23" or whatever), let me know so we could modify the regex accordingly.

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