寻找采用可能重复小数部分的任意数字的最佳方法,并发现重复部分(如果存在)。
最终,我需要用上划线表示法(用css text-decoration或MathML mline)来装饰数字,所以我需要知道重复开始的位置索引。
所以我需要正则表达式来获取(或者可以在算法中使用)以下结果:
1.333 // result: {"pattern": 3, index: 0}
1.5444 // result: {"pattern": 4, index: 1}
1.123123 // result: {"pattern": 123, index: 0}
1.5432121212 // result: {"pattern": 12, index: 4}
1.321 // result: null
1.44212 // result: null
附加示例(来自评论):
1.3333 // result: { "pattern": 3, index: 0}
答案 0 :(得分:4)
您可以尝试这样的事情:
(\d+?)\1+$
http://regex101.com/r/eX8eC3/3
它匹配了一些数字,然后使用反向引用尝试匹配相同的集合,然后立即进行1次或更多次。它固定在字符串的末尾,因为否则会被它绊倒,例如:
1.5432121212
会看到21
重复而不是12
。
将?
添加到第一个组以使其非贪婪应解决路易斯提出的1.3333
问题。
答案 1 :(得分:3)
function getRepetend(num) {
var m = (num+'').match(/\.(\d*?)(\d+?)\2+$/);
return m && {pattern: +m[2], index: m[1].length};
}
它的工作原理如下:
/\.(\d*?)(\d+)\2+$/
:
\.
匹配小数点。(\d*?)
匹配小数点和重复之间的数字,并将结果捕获到反序号1中。(\d+?)
匹配重复,并将其捕获到反向引号2中。\2+
匹配重复的重复。$
匹配字符串的结尾。null
(即无匹配),请返回null
。答案 2 :(得分:3)
您可以在结果对象中将此正则表达式与RexExp#exec
and use result.index
一起使用:
var re = /(\d+)\1$/;
var s = '.5439876543212211211';
var result = re.exec( s );
console.log ( result.index );
//=> 14
console.log ( result[1] );
//=> 211
答案 3 :(得分:1)