java - 检查中间字符串是否以某种模式开始-结束并更新字符串
问题描述
如果我有这样的字符串:
需要对字符串进行多次操作。我需要获取一个字符串并使用分隔符(“;”)提取不同的子字符串,然后再次提取不同的子字符串以使用分隔符形成键值(":")。如果针对键,它们的值不存在,则使用 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");
谁能指导我如何使用正则表达式获得结果。谢谢!!!!!!
解决方案
正如蒂姆所说,我们可以使用正则表达式模式来替换值。除了他的答案之外,我建议的唯一更改是在用于文本中的 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;
推荐阅读
- android - 如何在 Android 的 BOOT_COMPLETED 事件上启动后台服务?
- python - Python 3.9.1 argparse exit_on_error 在某些情况下不起作用
- redis - 使用 py-redis 在集合中插入元素期间出现问题
- db2 - 从 DBVisualizer 运行 XQuery 时出错
- python - 将 CSV 转换为数组 - Python
- windows - 为什么使用 New-PSSession 或 Enter-PSSession 存储副本故障转移失败
- pyomo - 为什么 CBC 找不到 Pyomo 热启动文件?
- javascript - 如何使用 TypeScript 使用自定义查询参数扩展默认 NextJS 路由器
- angular - 使用 ng2-pdf-viewer 加载本地 PDF
- java - quarkus 微服务中的性能问题