Currency / Percent Regular Expression

萝らか妹 提交于 2019-12-23 22:19:11

问题


I have to match values like

€ 6.483,00

OR values like

18,50%  

OR, again,

+65,86 %

in a Javascript function, which I drafted as:

function(s) {
  return /^[0-9]?[0-9,\.]*$/.test(s);
}

but, obviously, it's not working... how should it be changed?


回答1:


var sample = [
    "€ 6.483,00",
    "18,50%",
    "+65,86 %"
]
for(var i = 0; i < sample.length; i++) {
    var input = sample[i];
    var regex = /^(\u20ac ?)?\+?\d+(\.\d+)?(\,\d+)?( ?%)?$/
    console.log(input + "\t" + regex.test(input));
}

If there are cases that do not/should not match then let me know.




回答2:


^(?:€|\+)?\s*\d+(?:\.?\d{3})*(?:,\d+)?\s*%?\s*$

See it here on Regexr

Start of the string, an optional € or +, then optional whitespace, Then there should be at list one digit, followed by an optional dot and three digits, then an optional fraction, optional whitespace, optional % more optional whitespace and then the end of the string,



来源:https://stackoverflow.com/questions/7385145/currency-percent-regular-expression

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