[英]Regex match dates with special characters prefix
我有以下代碼:
var splitter = (filterValue.length > 0 ? filterValue.match(/^\s*(<|>)?\s*(\d\d\/\d\d\/\d{4})\s*\-?\s*(\d\d\/\d\d\/\d{4})?\s*$/).slice(1) : '');
filterValue
可以是:
01/01/2013
> 01/01/2013
< 01/01/2013
01/01/2013 - 01/01/2013
然后我將這些分成如下塊:
var string1 = (splitter.length > 0 ? splitter[0] : '');
var string2 = (splitter.length >= 2 ? splitter[1] : '');
var string3 = (splitter.length >= 3 ? splitter[2] : '');
var string4 = (splitter.length < 4 ? splitter[3] : '');
對於上面的例子'', '>', '<', ''
string1
可以是'', '>', '<', ''
。
string2
永遠是第一個日期
如果短划線存在於兩個日期之間,則string3
可以是''
或'-'
string4
將是最后一個日期。
但是我無法讓最后一個方案起作用。 所以假設我的正則表達式中有一個問題來處理這個問題。 有誰能看到這個問題?
小提琴: http : //jsfiddle.net/7LR49/1/
我越來越:
undefined
01/01/2013
01/01/2013
undefined
當我應該得到:
undefined
01/01/2013
-
01/01/2013
並在拆分器上顯示控制台:
[undefined, "01/01/2013", "01/01/2013"]
因此,最后一個第三個關鍵字並不是由正則表達式實際獲取的。 而取而代之的是第四位。
一些修復:
來自: /^\\s*(<|>)?\\s*(\\d\\d\\/\\d\\d\\/\\d{4})\\s*\\-?\\s*(\\d\\d\\/\\d\\d\\/\\d{4})?\\s*$/
至....: /^\\s*(<|>)?\\s*(\\d\\d\\/\\d\\d\\/\\d{4})\\s*(\\-)?\\s*(\\d\\d\\/\\d\\d\\/\\d{4})?\\s*$/
改變了: .................................^..^
true
所以你會忽略最后一組的價值: 來自: var string4 = (splitter.length < 4 ? splitter[3] : '');
至....: var string4 = (splitter.length < 5 ? splitter[3] : '');
改變了: ..............................^
現在輸出:
undefined
01/01/2013
-
01/01/2013
你的小提琴,更新: http : //jsfiddle.net/7LR49/2/
以下適用於我:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
var str = "> 01/01/2013 - 02/01/2013";
var regex = /\b(\d\d\/\d\d\/\d\d\d\d)\b/g;
var matches = getMatches(str, regex, 1);
alert(matches[0]);
alert(matches[1]);
OUTPUT:
01/01/2013
02/01/2013
該方法取自這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.