首页 > 解决方案 > 如何在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 的值;三。

标签: java

解决方案


对于单行解决方案,您可以使用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);

推荐阅读