javascript - 形成在重复小数内查找模式的正则表达式

标签 javascript regex unit-testing qunit

我怎样才能形成一个正则表达式来匹配在重复小数中重复的唯一数字?

目前我的正则表达式如下。

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"]);
});

最佳答案

好的。我采纳了 Joel 的建议,在某种程度上解决了我自己的问题。

问题在于正则表达式部分 (\d+)+(?:\1)$ 正在匹配最接近字符串末尾的模式,这使得它返回“9 ”,而不是字符串“0.099099099099099”的“099”。

我克服这个问题的方法是将匹配长度设置为 2 或更大,就像这样。

(\d{2,})+(?:\1)$,

并使用 /^(\d+)(?:\1)$/ 过滤结果,以防模式卡在模式中。

这是通过我所有测试用例的代码。

现场演示:http://jsfiddle.net/9dGsw/1/

var func = function( val ){
    val = (val || "").toString();
    var RE_PatternInRepeatDec = /(?:[^\.]+\.\d*)(\d{2,})+(?:\1)$/, 
        RE_RepeatingNums = /^(\d+)(?:\1)$/,
        match = RE_PatternInRepeatDec.exec( val );

    if( !match ){
        // Try again but take off last digit incase of precision error.
        val = val.replace( /\d$/, '' );
        match = RE_PatternInRepeatDec.exec( val );
    }
    if( match && 1 < match.length ){
        // Reset the match[1] if there is a pattern inside the matched pattern.
       match[1] = RE_RepeatingNums.test(match[1]) ? RE_RepeatingNums.exec(match[1])[1] : match[1];
    }
    return match;
};

感谢所有提供帮助的人。

关于javascript - 形成在重复小数内查找模式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10789435/

相关文章:

javascript - Angular 延迟加载模块错误 - 'RouterModule.forRoot() called twice'

javascript - 我如何使用 jquery 检查一个元素是否有任何子元素?

regex - 如何在 R 中使用正则表达式查找文本中最长的字符串

Python 使用 re.sub 删除后字符串。

javascript - 仅使用特定参数返回特定值

javascript - 如何让nock.js回复发布的数据?

javascript - 使用 jQuery 的动画径向渐变

javascript - PHP 视频流 Seekbar 在 Chrome 中不可用

Java - 如何使用匹配器编写可选的正则表达式模式

ios - 如何在 Xcode 中加载本地 json 文件以进行单元测试?