如何形成一个正则表达式来匹配以重复小数重复的唯一数字?
目前我的正则表达式如下。
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"]);
});