我有一串數字,例如:「1234」,並且我需要返回逗號分隔列表中每個數字的最大匹配數字組。使用正則表達式匹配項目的最大數量
在 「1000,1200,1330,1235」 將返回
["1", "12", "1", "123"]
感謝搜索 「1234」!
我有一串數字,例如:「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)
當然,像其他人所說我會如果可能的話,在這種特殊場景中傾斜於正則表達式解決方案。如果你實際上可以解析並將每個數字轉換爲數字類型,那麼這會更靈活,我想。
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