【问题标题】:Java Regex for custom function用于自定义函数的 Java 正则表达式
【发布时间】:2014-10-29 11:14:40
【问题描述】:

我正在寻找与以下匹配的正则表达式模式,但到目前为止我有点难过。我不知道如何抓取我想要的两组结果,标记为idattr

应该匹配:

  • account[id].attr
  • account[anotherid].anotherattr

这些应该分别返回id, attr,
anotherid, anotherattr

有什么建议吗?

【问题讨论】:

  • 我们可以看看你解决这个任务的尝试吗?您认为可以匹配account[xxx].yyy 的正则表达式可能是什么样的?
  • 似乎还不清楚。请多解释一下。
  • 我想我只想匹配 account[sometext].moretext 并获取 sometext 和 moretext 字段。似乎有可能!

标签: java regex match


【解决方案1】:

这是映射您的id -> attributes 的完整解决方案:

String[] input = {
        "account[id].attr",
        "account[anotherid].anotherattr"
};
//                           | literal for "account"
//                           |      | escaped "["
//                           |      |  | group 1: any character 
//                           |      |  |   | escaped "]"
//                           |      |  |   |  | escaped "."
//                           |      |  |   |  |  | group 2: any character
Pattern p = Pattern.compile("account\\[(.+)\\]\\.(.+)");
Map<String, String> output = new LinkedHashMap<String, String>();
// iterating over input Strings
for (String s: input) {
    // matching
    Matcher m = p.matcher(s);
    // finding only once per input String. Change to a while-loop if multiple instances
    // within single input
    if (m.find()) {
        // back-referencing group 1 and 2 as key -> value
        output.put(m.group(1), m.group(2));
    }
}
System.out.println(output);

输出

{id=attr, anotherid=anotherattr}

注意

在此实现中,"account[anotherid]." 等“不完整”输入将不会放入 Map,因为它们根本不匹配 Pattern

为了将这些案例写成id -> null,您只需在Pattern 的末尾添加?

这将使最后一组成为可选。

【讨论】:

  • hmm snag.gy/ZHHzk.jpg 显示不匹配...否则看起来不错!!
  • @phouse512 服务器,404。尽管使用 Java 测试您的 Java Patterns 与 Web 工具相比具有明显的优势,即实际看到它与 Java 正则表达式引擎匹配。
  • @phouse512 相同的答案(减去404):可能是不同的引擎,或者处理转义的不同方式(即单对双)。
猜你喜欢
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 2017-04-26
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
相关资源
最近更新 更多