使用正则表达式匹配项目的最大数量
问题描述:
我有一串数字,例如:“1234”,并且我需要返回逗号分隔列表中每个数字的最大匹配数字组。使用正则表达式匹配项目的最大数量
在 “1000,1200,1330,1235” 将返回
["1", "12", "1", "123"]
感谢搜索 “1234”!
答
这让我觉得最好的做法是编写自定义字符串分析器,而不是使用正则表达式。因此,例如,
function maxMatch(num) {
var s = num.toString();
var max = 0;
var n = 0;
for (var i = 0; i < s.length(); i++) {
if (s[i] == n) {
++n;
}
else if (s[i] == '1') {
n = '2';
}
else if (n != 0) {
max = parseInt(n) > max ? parseInt(n) : max;
n = 0;
}
}
return max;
}
我的JavaScript生锈(这是未经测试),但东西有点像,应该工作,并可能形成你的解决方案的一部分。
答
另一种方式与正则表达式来做到这一点:
(?<=\s|^)(1234|123|12|1)
当然,像其他人所说我会如果可能的话,在这种特殊场景中倾斜于正则表达式解决方案。如果你实际上可以解析并将每个数字转换为数字类型,那么这会更灵活,我想。
+0
JavaScript正则表达式不支持lookbehinds,但'\ b'会有相同的效果(假设逗号分隔的字符串永远不会包含字母或下划线)。 – 2009-08-11 06:19:32
答
String.prototype.matchChars= function(str){
var s= this, i= 0, L= this.length, tem= '';
while(i< L){
if(this[i]!= str[i]) return tem;
tem+= this[i];
i+= 1;
}
return tem;
}
function matchcharsinList(s, A){
if(typeof A== 'string') A= A.split(/, */);
for(var j= 0, n= A.length; j<n; j++){
tem= A[j] || '';
A[j]= s.matchChars(tem);
}
return A;
}
警报(matchcharsinList( '1234', '1000,1200,1330,1235'));
/*
A more useful method might allow case insensitive matches,, and a minimum length of a match:
*/
String.prototype.matchChars= function(str, min, ignorecase){
var s= this, i= 0, L= this.length, tem= '';
if(ignorecase){
s= s.toLowerCase();
str= str.toLowerCase();
}
if(min && str.substring(0, min)!= s.substring(0, min)) return '';
while(i< L){
if(this[i]!= str[i]) return tem;
tem+= this[i];
i+= 1;
}
return tem;
}
我不知道你需要什么可以通过常规的语言来表示,因此,不可能在一个正则表达式匹配。不是100%肯定的。 – wtaniguchi 2009-08-11 00:52:12