首页 > 解决方案 > 检查中间字符串是否以某种模式开始-结束并更新字符串

问题描述

如果我有这样的字符串: 需要对字符串进行多次操作。我需要获取一个字符串并使用分隔符(“;”)提取不同的子字符串,然后再次提取不同的子字符串以使用分隔符形成键值(":")。如果针对键,它们的值不存在,则使用 diff-diff 默认值进行更新,例如(“01/01/2000”,“01/01/1900”,因为两者都是日期类型)。 如果您注意到renewDate字段它们没有分隔符(“:”),在这种情况下,我们需要将分隔符与默认值(:01/01/1900)一起附加,以便我的预期结果如下:
String str = "startDate:23/04/2016;endDate:;renewDate;"




String str = "startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;"

我已经尝试过以下正则表达式,但它不适用于所有场景:

String regExpression = "(?<=\\bendDate:)[;]+" str = str.replaceAll(regExpression , "01/01/2000");

谁能指导我如何使用正则表达式获得结果。谢谢!!!!!!

标签: javaregexstring

解决方案


正如蒂姆所说,我们可以使用正则表达式模式来替换值。除了他的答案之外,我建议的唯一更改是在用于文本中的 renewDate 和 endDate 的模式中添加冒号(:) 作为可选。

    String endDate = "01/01/2000";
    String renewDate = "01/01/1900";
    String str = "startDate:23/04/2016;endDate:;renewDate;";
    str = str.replaceAll(";endDate:?;", ";endDate:"+endDate+";");
    str = str.replaceAll(";renewDate:?;", ";renewDate:"+renewDate+";");
    System.out.println(str); 

这将给出如下输出

startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;

推荐阅读