问题
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