Java使用正则表达式获取字符串中最后一个方括号之间的文本

Java使用正则表达式获取字符串中最后一个方括号之间的文本,java,regex,string,Java,Regex,String,我需要提取字符串最后一个括号之间的文本。这就是它的样子: String text= "[text1][text2][text3][text4]"; 我需要去 String result = "text4" 我试过用正则表达式,但没能成功。如果能帮我得到正则表达式和子字符串,我将不胜感激。非常感谢您不需要正则表达式。您可以使用lastIndexOf 使用正则表达式,.+\[.+\]$和capture group1 import java.util.reg

我需要提取字符串最后一个括号之间的文本。这就是它的样子:

String text= "[text1][text2][text3][text4]";
我需要去

String result = "text4"

我试过用正则表达式,但没能成功。如果能帮我得到正则表达式和子字符串,我将不胜感激。非常感谢

您不需要正则表达式。您可以使用lastIndexOf

使用正则表达式,.+\[.+\]$和capture group1

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String text = "[text1][text2][text3][text4]";
        Matcher matcher = Pattern.compile(".+(\\[.+\\])$").matcher(text);
        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}
输出:

有关正则表达式的解释,请访问:


我试过使用正则表达式,但我无法使它工作。。。请包括您尝试的Java代码,其缺席可能是所有否决票和关闭Votes的唯一原因,而不是正则表达式,我将使用lastIndexOf方法查找最后一个[和]。@TimBiegeleisen-@ArvindKumarAvinash 1我没有投票关闭该问题,但其他人投票关闭了,2 OP向我们展示了它已经尝试过的东西,这将为有人回答奠定基础。尽管我提出了要求,但那没有发生。
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String text = "[text1][text2][text3][text4]";
        Matcher matcher = Pattern.compile(".+(\\[.+\\])$").matcher(text);
        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}
[text4]