javascript regex optional minus

女生的网名这么多〃 提交于 2021-02-05 06:50:12

问题


I have the following function in javascript:

function unString(String){     
   var justNumbers = /(?=.*\d)\d*(?:\.\d*)?/;
   var result      = String.match(justNumbers);
   result *= 1;
   result = Math.round(result*100) / 100;
   return result;
}

The meaning of it is to extract the number out of every possible css value, so that it can be added or substracted or multiplied with other values: e. g.

var newPadding = unString(  $('#myID').css("padding-bottom")  )*10 + "px";

Having modified my code I would now need the regex to allow an optional minus, to allow values like "-3px" be transformed to "-3" (actually the function can't and returns "0").

[I know there are tons of optional minus regex threads on stackoverflow and other forums, but they don't match the form of my regex - I do not have much experience with regex, for creating the above one I had to do long and intense research - and so I could not modify my regex, referring to these]

[The regex is should allow digits, optional decimal point and optional minus]

Thx in advance


回答1:


You can use

/-?[0-9]*\.?[0-9]+/g

See the regex demo

Explanation:

  • -? - an optional hyphen (you may replace it with [-+]? to match both - and + optionally)
  • [0-9]* - zero or more digits
  • \.? - an optional dot
  • [0-9]+ - 1 or more digits.


来源:https://stackoverflow.com/questions/38523118/javascript-regex-optional-minus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!