【发布时间】:2020-10-26 14:50:54
【问题描述】:
任何人都可以帮助我使用执行以下操作的正则表达式:
- 只接受 0-9 的数字
- 仅接受以下只能出现一次的字符:“e”、“”和“.”
- 输入句号时,不能再输入逗号,反之亦然
- “e”后不得输入逗号或句点
我希望有人可以帮助我,我自己不擅长正则表达式,但知道它们很强大。但是,如果有其他方法可用,请告诉我。 我自己通过不同的方法尝试过。我写的不幸不能正常工作的代码如下:
validateNumberInput() {
this.countPeriods = 0
this.countCommas = 0
this.countE = 0
for (var i = 0; i <= this.inputValue.length; i++) {
if (
isNaN(this.inputValue[i]) &&
this.inputValue[i] &&
this.inputValue[i] != "." &&
this.inputValue[i] != "," &&
this.inputValue[i].toUpperCase() != "E"
) {
console.log(this.inputValue[i])
console.log(this.inputValue.length)
this.inputValue = this.inputValue.replace(this.inputValue[i], "")
} else if (this.inputValue[i] == "." && this.countPeriods < 1) {
this.countPeriods = this.countPeriods + 1
this.countCommas = this.countCommas + 1
} else if (this.inputValue[i] == "." && this.countPeriods >= 1) {
this.inputValue = this.inputValue.replace(this.inputValue[i], "")
} else if (this.inputValue[i] == ",") {
this.countCommas = this.countCommas + 1
this.countPeriods = this.countPeriods + 1
} else if (this.inputValue[i] == "E" || this.inputValue[i] == "e") {
this.countE = this.countE + 1
}
// Only accept a period, comma or 'e' once
if (this.inputValue[i] == "." && this.countPeriods > 1) {
this.inputValue = this.inputValue.replace(this.inputValue[i], "")
} else if (this.inputValue[i] == "," && this.countCommas > 1) {
this.inputValue = this.inputValue.replace(this.inputValue[i], "")
} else if ((this.inputValue[i] == "E" || this.inputValue[i] == "e") && this.countE > 1) {
this.inputValue = this.inputValue.replace(this.inputValue[i], "")
}
}
},
我遇到的问题是,如果句号、逗号或“e”已经出现过一次,并且我重新输入其中一个字符,则该字符会在其原始位置消失并被新字符替换。应该是这样的,如果已经输入了这些字符之一,我就不能再输入这些字符了
【问题讨论】:
-
你的代码有一个bug:当你解析输入“abc”时,i=0,你删除了“a”,留下了inputValue="bc"。现在你前进到 i=1,检查“c”,删除它留下 inputValue="b"。现在您访问 inputValue[1] 来测试周期。程序崩溃。要更正,您可以将 inputValue[i] 存储在临时变量中,并且仅在测试表达式中使用此变量。
标签: javascript numbers character expression