如何形成一個正則表達式,以匹配重複小數點中重複的唯一數字?Form Regex在重複小數內找到模式
目前我的正則表達式如下。
var re = /(?:[^\.]+\.\d*)(\d+)+(?:\1)$/;
例子:
// Pass
deepEqual(func(1/111), [ "0.009009009009009009", "009" ]);
// Fails, since func(11/111) returns [ "0.099099099099099", "9" ]
deepEqual(func(11/111), [ "0.099099099099099", "099" ]);
現場演示這裏:http://jsfiddle.net/9dGsw/
這裏是我的代碼。
// Goal: Find the pattern within repeating decimals.
// Problem from: Ratio.js <https://github.com/LarryBattle/Ratio.js>
var func = function(val){
var re = /(?:[^\.]+\.\d*)(\d+)+(?:\1)$/;
var match = re.exec(val);
if(!match){
val = (val||"").toString().replace(/\d$/, '');
match = re.exec(val);
}
return match;
};
test("find repeating decimals.", function() {
deepEqual(func(1), null);
deepEqual(func(1/10), null);
deepEqual(func(1/111), [ "0.009009009009009009", "009" ]);
// This test case fails...
deepEqual(func(11/111), [ "0.099099099099099", "099" ],
"What's wrong with re in func()?");
deepEqual(func(100/111), [ "0.9009009009009009", "009"]);
deepEqual(func(1/3), [ "0.3333333333333333", "3"]);
});
它會更好地逃脫點,以使你的意圖匹配一個點(而不是任何東西)明確 –
我已經糾正它。 –