【问题标题】:Return all occurrences of a substring [duplicate]返回所有出现的子字符串[重复]
【发布时间】:2019-01-01 12:55:44
【问题描述】:

我有以下字符串值;

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

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

我知道我可以使用:

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

返回 col = at 但我不确定如何获得所有三个。感谢您的帮助。

【问题讨论】:

  • col = 后面总是只有两个字母吗?
  • 没有变化,我只是为这个例子简化了它们
  • 你能不能先用",\\s+"分割,然后再用"\\s+=\\s+"分割,然后选择第一个元素是"col"的任何对?这对你有用吗?
  • @matt 你只是想在 = 符号或整个 col = 之后提取值
  • 我试图拉出整个 col =

标签: java substring


【解决方案1】:

可以通过 Streams 实现:

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 = 在 col = me col = fg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2015-09-17
    相关资源
    最近更新 更多