javascript - Further Regex sums -
with regex: /((-|\+)?([0-9]+|)(\.?[0-9]+))/g can use array.prototype.reduce sum numbers var str = 'hello +0.50 world hello 1 world hello -10 world', re = /((-|\+)?([0-9]+|)(\.?[0-9]+))/g, sum; sum = (str.match(re) || []).reduce(function (prev, current) { if (object.prototype.tostring.call(prev) !== '[object number]') { prev = parsefloat(prev, 10); } return prev + parsefloat(current, 10); }, 0); // sum should equal -8.5 here note `str.match(re)` may return `null`, make sure call `reduce` on array.
i wondering if possible ignore things in brackets, there.
here example of strings added together:
+0.08 attack damage per level (+1.35 @ champion level 18)
it current adds in string, yes - did ask for, doesn't add 0.08
, 1.35
itself, merges them together.
i'd either them separate, 1 in brackets , 1 isn't or ignore content within brackets. (content after "level .." within brackets should ignored in cases)
to keep first number maybe try:
^((-|\+)?([0-9]+|)(\.?[0-9]+))
or simpler
^((-|\+)?\d*\.?\d*)
remember use capture groups if want more 1 matches. http://www.regular-expressions.info/brackets.html
Comments
Post a Comment