[英]How to get match within [ and ] in String using regex
I have a requirement to get the matching string within square brackets []. 我需要在方括号[]中获取匹配的字符串。
For eg., in a String input like "[***]qwerty"
, I should get the match as "***"
string. 例如,在像
"[***]qwerty"
这样的字符串输入中,我应该将匹配作为"***"
字符串。
The regex I used in vain is "\\\\[(.+)\\\\]"
我徒劳无功的正则表达式是
"\\\\[(.+)\\\\]"
My Java code is as below: 我的Java代码如下:
Pattern pattern = Pattern.compile(regex_custom_delimiter_pattern); //see regex above
Matcher matcher = pattern.matcher("[***]qwerty");
String delimiter = null;
if (matcher.find()) {
delimiter = matcher.group(0);
}
Any help is appreciated..wondering what I'm missing in the regex that I used :( 任何帮助是值得赞赏的..想想我在使用的正则表达式中缺少的东西:(
That should work correctly, but you can use a more efficient expression if the value between [
and ]
doesn't contain [
or ]
literally: 这应该可以正常工作,但如果
[
和]
之间的值不包含[
或]
字面意思,则可以使用更高效的表达式:
\\[([^\\]]+)]
Or if the value can contain [
or ]
then: 或者,如果值可以包含
[
或]
则:
\\[(.+?)\\]
Also your main problem is that you are getting group 0 matcher.group(0)
which is the entire match, your value is stored in group 1 so you need matcher.group(1)
. 另外你的主要问题是你得到的是第0组
matcher.group(0)
这是整个匹配,你的值存储在第1组中所以你需要matcher.group(1)
。
您需要组1而不是组0.组0是整个匹配。
delimiter = matcher.group(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.