【问题标题】:java regular expression to extract content within square bracketsjava正则表达式提取方括号内的内容
【发布时间】:2023-04-05 11:14:01
【问题描述】:

输入线在下方

Item(s): [item1.test],[item2.qa],[item3.production]

你能帮我写一个Java正则表达式来提取吗

item1.test,item2.qa,item3.production

从上面的输入行?

【问题讨论】:

    标签: java regex


    【解决方案1】:

    更简洁一点:

    String in = "Item(s): [item1.test],[item2.qa],[item3.production]";
    
    Pattern p = Pattern.compile("\\[(.*?)\\]");
    Matcher m = p.matcher(in);
    
    while(m.find()) {
        System.out.println(m.group(1));
    }
    

    【讨论】:

    • 你能解释一下这个模式的含义吗?谢谢
    【解决方案2】:

    您应该使用积极的前瞻和后视:

    (?<=\[)([^\]]+)(?=\])
    
    • (? 的所有内容
    • ([^]]+) 匹配任何不包含]的字符串
    • (?=]) 匹配 ]​​i> 之前的所有内容

    【讨论】:

    • 太棒了,但我怎样才能得到相反的结果呢?我只想保留方括号内的内容
    • 我不明白你的问题 - 这正是这个正则表达式所做的。接受输入 Item(s): [item1.test],[item2.qa],[item3.production] 它返回 item1.test item2.qa item3.production
    【解决方案3】:

    我会在修剪前面或后面的垃圾后拆分:

    String s = "Item(s): [item1.test], [item2.qa],[item3.production] ";
    String r1 = "(^.*?\\[|\\]\\s*$)", r2 = "\\]\\s*,\\s*\\[";
    String[] ss = s.replaceAll(r1,"").split(r2);
    System.out.println(Arrays.asList(ss));
    // [item1.test, item2.qa, item3.production]
    

    【讨论】:

    • @Stephan Kristyn:在 Mac OS X 10.6.7 上的 Java 1.6 上为我工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多