Das erforderliche Datenformat ist:
1
10
100
1-5
10-50
100-500
0,5
10,5
10,5-20
10,5-20,5
10-20,5
Das hei?t, die Gr??e der für die Verifizierung erforderlichen Zahl ist nicht begrenzt, sie kann Gleitkommazahlen haben oder nicht, sie kann ?-“ haben oder nicht, und eine Dezimalstelle bleibt erhalten
Dies ist der regul?re Ausdruck, den ich geschrieben habe:
Die folgende Kopie ist falsch:
var a=/^\d{1,}\.?\d?-?(\d{1,})?\.?\d?$/;
Korrigiert zu:
var a=/^\d{1,}\.?\d{1}?-?(\d{1,})?\.?\d{1}?$/;
Aber warum ist 20,5555 immer wahr?
Following the voice in heart.
/^\d{1,}\.?\d?-?(\d{1,})?\.?\d?$/
匹配過程如下:
首先d{1,}
匹配的是"20";\.?
匹配".";\d?
匹配"5",?
匹配了1次;-?
匹配"",因?yàn)?code>?匹配0或者1次,在這里匹配0次;(\d{1,})?
匹配"555",此時(shí)?
匹配1次;\.?\d?
匹配"",此時(shí)兩個(gè)?
都匹配0次;$
匹配字符串結(jié)尾,所以"20.5555"可以匹配。
Update1:/^\d{1,}\.?\d{1}?-?(\d{1,})?\.?\d{1}?$/
的匹配過程如下:
\d{1,}
匹配"20";
\.?
匹配".";
\d{1}?
會(huì)首先嘗試匹配一個(gè)數(shù)字,此時(shí)匹配"5",?
匹配1次;
-?
會(huì)匹配"",此時(shí)?
匹配0次;
(\d{1,})?
匹配"555";
\.?
匹配"",此時(shí)?
匹配0次;
\d{1}?
匹配"",?
匹配0次;\d{1}
表示數(shù)字重復(fù)一次,所以該正則和\d
其實(shí)是一樣的,所以更新后的正則表達(dá)式和原先的正則表達(dá)式?jīng)]有區(qū)別。
注:一開始寫的匹配過程有點(diǎn)兒問題,現(xiàn)在已經(jīng)更新。
const regex = /^\d+(?:\.\d)?(?:-\d+(?:\.\d)?)?$/;
const cases = [
"1",
"10",
"100",
"1-5",
"10-50",
"100-500",
"0.5",
"10.5",
"10.5-20",
"10.5-20.5",
"10-20.5",
"20.5555",
"20.5-20.5555"
];
const r = cases.map(s => regex.test(s));
console.log(r);