gpt4 book ai didi

java - 使用正则表达式匹配模式,排除某些字符

转载 作者:行者123 更新时间:2023-11-30 03:03:51 24 4
gpt4 key购买 nike

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

例如:

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

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

\[.*?\]

除了在匹配中还包含括号之外,它工作得很好。所以我得到的结果是:

[the substring I want]

而不是

the substring I want

是的,之后我可以很容易地去掉括号,但是有什么办法可以完全不匹配它们吗?

最佳答案

使用“环顾四周”:

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

关于java - 使用正则表达式匹配模式,排除某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com