RegEx帮助替换substring

时间:2014-02-10 11:44:17

标签: java regex pattern-matching

我有一个字符串:

StartTime-2014-01-14 12:05:00-StartTime

要求是用当前时间戳替换时间戳。

我尝试了下面的代码,它没有给我预期的输出:

String st = "StartTime-2014-01-14 12:05:00-StartTime"; 
String replace = "StartTime-2014-01-14 13:05:00-StartTime"; 
Pattern COMPILED_PATTERN = Pattern.compile(st, Pattern.CASE_INSENSITIVE); 
Matcher matcher = COMPILED_PATTERN.matcher(DvbseContent); 
String f = matcher.replaceAll(replace);

预期输出为:

StartTime-<Current_Time_stamp>-StartTime

2 个答案:

答案 0 :(得分:0)

您可以这样匹配:

(StartTime-).*?(-StartTime)

并将其替换为此(或类似):

"$1" + current_time_stamp + "$2"

Example Java Code:

import java.util.*;
import java.util.Date;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        java.util.Date timestamp = new java.util.Date();
        String search = "StartTime-2014-01-14 12:05:00-StartTime";
        String regex = "(StartTime-).*?(-StartTime)";
        String replacement = "$1"+ timestamp + "$2";
        String result = search.replaceAll(regex, replacement);

        System.out.println(result);
    };
};

输出:

  

StartTime-Fri Feb 14 08:53:57 GMT 2014-StartTime

答案 1 :(得分:0)

或者代替Regex,您可以使用indexOf和lastIndexOf:

String f = "StartTime-2014-01-14 12:05:00-StartTime";
String timestamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                  .format(new java.util.Date());
String newString = f.substring(0, f.indexOf("-") + 1) 
                + timestamp 
                + f.substring(f.lastIndexOf("-"));

输出: StartTime-2014-02-10 12:52:47-StartTime