[英]RegEx help to replace substring
我有一個字符串:
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
您可以這樣匹配它:
(StartTime-).*?(-StartTime)
並替換為以下(或類似內容):
"$1" + current_time_stamp + "$2"
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 2月14日08:53:57 GMT 2014-StartTime
或代替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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.