Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java从方括号中获取子字符串_Java_Regex - Fatal编程技术网

Java从方括号中获取子字符串

Java从方括号中获取子字符串,java,regex,Java,Regex,我试图从一个字符串的方括号中获取一个子字符串,我尝试了多个正则表达式,但都不起作用 String mydata = "some string with [the data i want] inside"; Pattern pattern = Pattern.compile("[(.*?)]"); Matcher matcher = pattern.matcher(mydata); if (matcher.find()) { System.out.println(matcher.group

我试图从一个字符串的方括号中获取一个子字符串,我尝试了多个正则表达式,但都不起作用

String mydata = "some string with [the data i want] inside";
Pattern pattern = Pattern.compile("[(.*?)]");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(1));
    output = output.replace("%item%", matcher.group(1));
}
我从多个stackoverflow帖子中尝试了多个正则表达式和代码,但没有任何效果

String mydata = "some string with [the data i want] inside";
Pattern pattern = Pattern.compile("[(.*?)]");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(1));
    output = output.replace("%item%", matcher.group(1));
}

它应该返回“我想要的数据”,但它表示没有找到任何模式。

您需要转义
[]
字符,以便将它们视为文字方括号


将此用作正则表达式应该可以工作:
\\[(.*?\\\]

[
必须转义以匹配文本
[
字符。请参阅Try@WiktorStribiż如果之前没有打开的括号,则关闭的括号将自动转义?@Cid无需转义
]
正则表达式引擎知道它是否关闭了字符类。但是在Java正则表达式中的字符类中,
[
]
都必须转义。@WiktorStribiżew nice,我学到了一些新东西。正则表达式引擎真的很聪明:)非常感谢!它工作了