【问题标题】:JAVA - How to get String in ${} [duplicate]JAVA - 如何在 ${} 中获取字符串 [重复]
【发布时间】:2016-03-28 17:07:25
【问题描述】:

例如:

String str = "bla bla ${foo} ${foo1}";

如何得到单词“foo”和“foo1”?

也许我的字符串是:

String str1 = "${foo2} bla bla ${foo3} bla bla";

如何得到单词“foo2”和“foo3”?

【问题讨论】:

  • 一种解决方案是使用正则表达式。
  • 你写了什么代码?它有什么作用?帮助我们重现您的问题。
  • 我自己会在 Google 上搜索“java 提取括号之间的文本”。这个answer 显示为第一个结果。
  • Pattern + Matcher 会有所帮助。
  • 谢谢大家,我找到了一些解决方案。使用模式 + 匹配器。

标签: java


【解决方案1】:

您可以使用正则表达式 PatternMatcher 类。例如:

String str = "bla bla ${foo} ${foo1}";
Pattern p = Pattern.compile("\\$\\{([\\w]+)\\}");
Matcher m = p.matcher(str);
while(m.find()) {
    System.out.println(m.group(1));
}
/* Result:
foo
foo1
 */

【讨论】:

    【解决方案2】:
    Pattern p = Pattern.compile("\\${(.*?)\\}");
    Matcher m = p.matcher(input);
    while(m.find())
    {
        //m.group(1) is your string. do what you want
    }
    

    这应该可以工作

    【讨论】:

      猜你喜欢
      • 2011-04-24
      • 1970-01-01
      • 2014-05-12
      • 2015-11-04
      • 2019-03-16
      • 2016-02-28
      • 2011-05-25
      • 1970-01-01
      • 2019-09-13
      相关资源
      最近更新 更多