java - 如何在java中提取以特定字符串开头的部分字符串
问题描述
我在java中有一个字符串
String s="a=one b=two c=three d=four e=five"
我想打印 c ie 的值;三。
我拿了 StringTokenizer,我得到了。
a=one
b=two
c=three
d=four
e=five
我想打印 c ie 的值;三。
解决方案
对于单行解决方案,您可以使用String#replaceAll
:
String input = "a=one b=two c=three d=four e=five";
String cValue = input.replaceAll(".*\\bc=(.+?)\\b.*", "$1");
System.out.println("c: " + cValue);
这打印:
c: three
如果您想采用拆分为键值对数组的路线,请考虑使用流:
String input = "a=one b=two c=three d=four e=five";
String cValue = Arrays.stream(input.split("\\s+"))
.filter(x -> "c".equals(x.split("=")[0]))
.map(x -> x.split("=")[1])
.collect(Collectors.toList())
.get(0);
推荐阅读
- java - 有条件地在 XML 中包含 bean?
- python - SOL_SOCKET 和 SOL_REUSE
- datepicker - ERROR 错误:mat-form-field 必须包含 MatFormFieldControl
- java - EntityListener 是否在同一个线程中运行?
- inkscape - Inkscape:重置第一个节点
- java - Java lambda 方法和新对象
- sql - Postgres 查询 - 计算最繁忙的 1 小时时段
- ruby-on-rails - 返回用户结帐时加载已保存的记录,例如地址或邮政记录
- mysql - MySQL for Visual Studio,无法加载存储过程进行编辑
- css - 如果 Bootstrap CSS 已链接,则自定义 CSS 样式规则仅在添加到样式标签时适用