2016-01-01 30 views
1

我有下面的java腳本來提取字符串中出現「=」後的單詞。正則表達式解釋

例如:

string strOld="ActionDate=11/20/2014 12:00:00 AM "; 

strOld.substr(strOld.indexOf(type)).substr(type.length +1, strOld.substr(strOld.indexOf(type)).substr(type.length).indexOf(" ")) 

這將提取「2014年11月20日」,從上述string.Since這是被「=」後存在的單詞。

如何使用正則表達式重寫?

我想要在同一個字符串變量中重新出現「=」的情況下得到逗號分隔的日期。

在有多個標誌的情況下:

輸入:字符串strOld = 「ActionDate = 11/20/2014年12:00:00 AM SuspensionCode = 123」; 輸出: 「11/20/2014,123」

回答

3

這是一個JavaScript版本

https://fiddle.jshell.net/nsqbuy11/1/

也是剛剛纔知道jshell,似乎一個很好的工具

var myregexp = /=(\S*)/g; 
var match = myregexp.exec("FirstEvictionActionDate=11/20/2014 12:00:00 AM SuspensionCode=123"); 
while (match != null) { 
    //for (var i = 0; i < match.length; i++) { 
    alert((match[1])); 
    //} 
    match = myregexp.exec("FirstEvictionActionDate=11/20/2014 12:00:00 AM SuspensionCode=123"); 
} 
+0

你能寫完整的代碼嗎? – SmartestVEGA

+0

@buckley這個'=(\ S +)'就夠了。而且你還必須加上'g'修飾符。 –

+0

單件作品,但多個我把以下表達,但它不工作 – SmartestVEGA

1

首先拆分字符串轉換爲數組,然後從數組中的第二項提取日期,即日期時間字符串。

var strOld = "ActionDate=11/20/2014 12:00:00 AM"; 
var arr = strOld.split('='); 
var regex = /([\d]{2}\/[\d]{2}\/[\d]{4})\s([\d]{2}:[\d]{2}:[\d]{2}\s(AM|PM))/; 
var result; 
arr[1].replace(regex, function(date, time) { 
    result = date; 
    console.log(result); 
}); 
1

如果你不關心這個詞來平等的左側,那麼你可以使用這個表達式來分割它:

'ActionDate=11/20/2014 12:00:00 AM SuspensionCode=123'.split(/\w+=/); 
// result: ["", "11/20/2014 12:00:00 AM ", "123"] 

,或者如果你想將它們包括在陣列中,試試這個:

'ActionDate=11/20/2014 12:00:00 AM SuspensionCode=123'.split(/(\b\w+)=/) 
// result ["", "ActionDate", "11/20/2014 12:00:00 AM ", "SuspensionCode", "123"]