在特定的其他子字符串之后获取子字符串的最有效方法

Most efficient way to get the substring after a specific other substring

如果我有一个看起来像这样的字符串:

String text = "id=2009,name=Susie,city=Berlin,phone=0723178,birthday=1991-12-07";

我只想获得信息 namephone。我知道如何解析整个字符串,但在我的具体情况下,重要的是只获取这两个 "fields".

那么 best/most 让我的搜索方法执行以下操作的有效方法是什么:

搜索子字符串 "name=" 和 return 其后的子字符串 ("Susie") 直到到达下一个逗号

我的方法是:

  1. 首先获取"name="的最后一个索引
  2. 然后使用此索引作为我的解析方法的新起点

关于如何使用更简洁的代码更有效地完成此操作,还有其他建议吗?感谢您的任何输入

您可以使用以下正则表达式来捕获 phonename 之后的预期单词,并从匹配的对象中获取第一个组:

(?:phone|name)=([^,]+)

关于以下命令,如果它可能碰巧有一个包含 phonename 的单词,作为更全面的方式,您可以在您的名字前加上逗号。

(?:^|,)(?:phone|name)=([^,]+)

详细了解正则表达式 http://www.regular-expressions.info/

正则表达式可能更有效,但为了可读性,我 <3 Guava

    String text = "id=2009,name=Susie,city=Berlin,phone=0723178,birthday=1991-12-07";

    final Map<String, String> infoMap = Splitter.on(",")
            .omitEmptyStrings()
            .trimResults()
            .withKeyValueSeparator("=")
            .split(text);

    System.out.println(infoMap.get("name"));
    System.out.println(infoMap.get("birthday"));