RegEx 进行成本字段验证
RegEx making a cost field validation
我可以在正则表达式变量中使用什么来确保字段仅包含数字,但还允许句号(句点)和各种货币符号(£、$)
希望能帮到你!
谢谢
这是我目前的情况:
var validRegExp = /^[0-9]$/;
我可能会选择以下内容:
/^\d+(\.[\d]+){0,1}[€$]{0,1}$/gm
它匹配至少一位数字,然后允许您在其中某处放置零或一个句点,然后在句点之后至少需要一位数字。在它的末尾,您可以放置一个明确命名的货币符号。你必须添加所有你想要支持的。
让我们尝试以下列表:
3.50€
2$
.5
34.4.5
2$€
afasf
您会看到只有前两个匹配正确。您的最终输出是组 0 中的输出。
const regex = /^\d+(\.[\d]+){0,1}[€$]{0,1}$/gm;
const str = `3.50€
2$
.5
34.4.5
2$€
afasf
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
我可以在正则表达式变量中使用什么来确保字段仅包含数字,但还允许句号(句点)和各种货币符号(£、$)
希望能帮到你!
谢谢
这是我目前的情况:
var validRegExp = /^[0-9]$/;
我可能会选择以下内容:
/^\d+(\.[\d]+){0,1}[€$]{0,1}$/gm
它匹配至少一位数字,然后允许您在其中某处放置零或一个句点,然后在句点之后至少需要一位数字。在它的末尾,您可以放置一个明确命名的货币符号。你必须添加所有你想要支持的。
让我们尝试以下列表:
3.50€
2$
.5
34.4.5
2$€
afasf
您会看到只有前两个匹配正确。您的最终输出是组 0 中的输出。
const regex = /^\d+(\.[\d]+){0,1}[€$]{0,1}$/gm;
const str = `3.50€
2$
.5
34.4.5
2$€
afasf
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}