【问题标题】:Match pattern with regex excluding certain characters [duplicate]匹配模式与正则表达式不包括某些字符[重复]
【发布时间】:2016-05-19 19:20:21
【问题描述】:

我想使用正则表达式创建包含“[”和“]”括号之间的字符但不包含括号本身的子字符串。

例如:

This is a String with [the substring I want].

我使用的正则表达式如下:

\[.*?\]

它工作正常,除了它还包括匹配中的括号。所以我得到的结果是:

[the substring I want]

而不是

the substring I want

是的,之后我可以很容易地摆脱括号,但是有什么办法根本不匹配它们吗?

【问题讨论】:

    标签: java regex


    【解决方案1】:

    使用“环视”:

    String test = "This is a String with [the substring I want].";
    //                          | preceding "[", not matched
    //                          |      | any 1+ character, reluctant match
    //                          |      |  | following "]", not matched
    //                          |      |  | 
    Pattern p = Pattern.compile("(?<=\\[).+?(?=\\])");
    Matcher m = p.matcher(test);
    if (m.find()) {
        System.out.println(m.group());
    }
    

    输出

    the substring I want
    

    【讨论】:

    • 非正则表达式的方式是:System.out.println(test.substring(test.indexOf("[") + 1, test.indexOf("]")));跨度>
    • @Arqan 不客气
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    相关资源
    最近更新 更多