gpt4 book ai didi

java - 从括号中获取字符串的正则表达式?

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:19 25 4
gpt4 key购买 nike

我有以下字符串:

"The girl with the dragon tattoo (LISBETH)"

我需要在输入的末尾仅获取括号中的字符串

到目前为止我是这样的:

    public static void main(String[] args) {

Pattern pattern =
Pattern.compile("\\({1}([a-zA-Z0-9]*)\\){1}");

Matcher matcher = pattern.matcher("The girl with the dragon tattoo (LISBETH)");

boolean found = false;
while (matcher.find()) {
System.out.println("I found the text " + matcher.group()
+ " starting at " + "index " + matcher.start()
+ " and ending at index " +
matcher.end());
found = true;
}
if (!found) {
System.out.println("No match found");
}
}

但结果我得到:(LISBETH)

如何摆脱这些括号?

谢谢!

最佳答案

使用这个模式:\\((.+?)\\) 然后得到组 1

public static void main(String[] args) {

Pattern pattern = Pattern.compile("\\((.+?)\\)");
Matcher matcher = pattern.matcher("The girl with the dragon tattoo (LISBETH)");

boolean found = false;
while (matcher.find()) {
System.out.println("I found the text " + matcher.group(1)
+ " starting at " + "index " + matcher.start()
+ " and ending at index " +
matcher.end());
found = true;
}
if (!found) {
System.out.println("No match found");
}
}

关于java - 从括号中获取字符串的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9990053/

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