2016-06-21 54 views
0

我有一個字符串,其中包含以下日期範圍格式變體。我需要使用單個java正則表達式來查找並替換爲小時精度。日期範圍是可變的。你能爲我提供一個正則表達式嗎?用於更新日期精度的正則表達式

String示例

published_date:{5月31日/ 16.23:41:24-?}

published_date:{5月31日/ 16.23:41:24-06/21/16.23: 41:24}

預期結果

published_date:{5月31日/ 16.23:00:00-}

published_date:{5月31日/ 16.23:00:00-06/21/16.23:00:00}

回答

2

說明

此正則表達式會發現子,看起來像日期/時間戳一樣05/31/16.23:41:24。它會捕獲日期和小時部分,並允許您用00替換分​​鍾和秒鐘。

([0-9]{2}\/[0-9]{2}\/[0-9]{2}\.[0-9]{2}):[0-9]{2}:[0-9]{2} 

替換爲:$1:00:00

Regular expression visualization

現場演示

https://regex101.com/r/qK8bL7/1

示例文本

published_date:{05/31/16.23:41:24-?} 

published_date:{05/31/16.23:41:24-06/21/16.23:41:24} 

更換

published_date:{05/31/16.23:00:00-?} 

published_date:{05/31/16.23:00:00-06/21/16.23:00:00} 

說明

NODE      EXPLANATION 
---------------------------------------------------------------------- 
    (      group and capture to \1: 
---------------------------------------------------------------------- 
    [0-9]{2}     any character of: '0' to '9' (2 times) 
---------------------------------------------------------------------- 
    \/      '/' 
---------------------------------------------------------------------- 
    [0-9]{2}     any character of: '0' to '9' (2 times) 
---------------------------------------------------------------------- 
    \/      '/' 
---------------------------------------------------------------------- 
    [0-9]{2}     any character of: '0' to '9' (2 times) 
---------------------------------------------------------------------- 
    \.      '.' 
---------------------------------------------------------------------- 
    [0-9]{2}     any character of: '0' to '9' (2 times) 
---------------------------------------------------------------------- 
)      end of \1 
---------------------------------------------------------------------- 
    :      ':' 
---------------------------------------------------------------------- 
    [0-9]{2}     any character of: '0' to '9' (2 times) 
---------------------------------------------------------------------- 
    :      ':' 
---------------------------------------------------------------------- 
    [0-9]{2}     any character of: '0' to '9' (2 times) 
---------------------------------------------------------------------- 
0

後試試這個。 「:[0-9] +:[0-9] +」。

公共類的正則表達式{

public static void main(String ar[]){ 
    String st = "05/31/16.23:41:24-06/21/16.23:41:24"; 

    st = st.replaceAll(":[0-9]+:[0-9]+", ":00:00"); 
    System.out.println(st); 

    st = "05/31/16.23:41:24-?"; 

    st = st.replaceAll(":[0-9]+:[0-9]+", ":00:00"); 
    System.out.println(st); 

} 

}