返回所有出现的子串

时间:2018-07-24 19:46:27

标签: java substring

我有以下字符串值;

 String value = "col = at, ud = sam, col = me, od = tt, col = fg";

我只需要返回col = at col = me和col = fg;

我知道我可以使用:

value.substring(0, value.indexOf(",")

返回col = at,但是我不确定如何获取全部三个。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

可以通过流实现:

List<String> results = Arrays.stream(value.split(","))
.map(String::trim)
.filter(val-> !val.isEmpty() && val.startsWith("col ="))
.collect(Collectors.toList())

您还可以使用正则表达式:

String value = "col = at, ud = sam, col = me, od = tt, col = fg";

Pattern pattern = Pattern.compile("col\\s+=\\s+\\w++");

List<String> allMatches = new ArrayList<String>();
Matcher m = pattern.matcher(value);
while (m.find()) {
   allMatches.add(m.group());
}
allMatches.forEach(System.out::print); 

输出:

  

col = at col = me col = fg

相关问题