[英]RegEx help to replace substring
I have a String: 我有一个字符串:
StartTime-2014-01-14 12:05:00-StartTime
The requirement is to replace the timestamp with current timestamp. 要求是用当前时间戳替换时间戳。
I tried the below code which is not giving me the expected output: 我尝试了下面的代码,但没有给我预期的输出:
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);
Expected Output is: 预期输出为:
StartTime-<Current_Time_stamp>-StartTime
You could match it like this: 您可以这样匹配它:
(StartTime-).*?(-StartTime)
and replace it with this (or similar): 并替换为以下(或类似内容):
"$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);
};
};
Output: 输出:
StartTime-Fri Feb 14 08:53:57 GMT 2014-StartTime
StartTime-Fri 2月14日08:53:57 GMT 2014-StartTime
Or instead of Regex, you can just use indexOf and lastIndexOf: 或代替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("-"));
Output: StartTime-2014-02-10 12:52:47-StartTime 输出:StartTime-2014-02-10 12:52:47-StartTime
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.