Java Regexp从String中获取所有变量

时间:2016-01-31 09:18:19

标签: java regex

我的字符串看起来像这样:

String input = "I have a $personInstance.first_name, but I like    $personInstance.last_name dog better.";

我需要验证字符串中的变量。如何使用java正则表达式匹配器从文本中解析它们。

我希望得到以上字符串:

personInstance.first_name
personInstance.last_name

有人知道如何编写模式吗?

Pattern p = Pattern.compile("HOW SHOULD THIS LOOK LIKE??");
    Matcher m = p.matcher(input);
    List<String> animals = new ArrayList<String>();
    while (m.find()) {
        System.out.println("Found a " + m.group() + ".");
        animals.add(m.group());
    }

2 个答案:

答案 0 :(得分:1)

很简单

    String input = "I have a $personInstance.address, but I like    $personInstance.last_name dog better.";

    Pattern p = Pattern.compile("\\$(\\w+\\.\\w+)");
    Matcher m = p.matcher(input);
    while (m.find()) {
        System.out.println("Found a " + m.group(1));
        //use m.group(0) vs m.group(1) if you want $ to be returned as well
    }

说明:

  • \\$:匹配$(以我们在开始时的$开头)
  • \\w:匹配a-z,A-Z,0-9,_(下划线)
  • \\.:匹配。 (点)
  • ():捕获组中的匹配项(如果您需要从输出中删除$)
  • +:匹配任意次数

答案 1 :(得分:0)

String input = "I have a $person.Instance.address, but I like    $personInstance.last_name dog better.";

Pattern p = Pattern.compile("\\$[^\\s\\,\\$]+");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.println("Found a " + m.group());
}

更新了到“\ $ [^ \ s \,\ $] +”(以避免将相邻的令牌匹配为一个)