[英]regex - Java Regular expression matching square bracket
Would someone kindly demonstrate what the regular expession would be for matching the square brackets? 有人可以证明匹配方括号的常规支出是什么吗?
I'm currently using java.util.regex
. 我目前正在使用
java.util.regex
。
For example, let's say we have the following line: 例如,假设我们有以下行:
public static void main (String[] args) {
I need to match only the OPEN square bracket [
and next, the close square bracket ]
. 我只需要匹配OPEN方括号
[
和接下来的close方括号]
。
I'm not saying I need to match the text between the square brackets. 我并不是说我需要在方括号之间匹配文本。
I have tried with 我尝试过
[\\]]
and 和
\\]
Unfortunately, it matches the text as well and I need to match only [
or ]
. 不幸的是,它也匹配文本,我只需要匹配
[
或]
。
The weird thing is, when I try to match the {
with [\\\\}]
, it works! 奇怪的是,当我尝试将
{
与[\\\\}]
匹配时,它起作用了!
Thoughts? 有什么想法吗?
You can do it using: 您可以使用:
String text = "[This is the text]";
String patternString = "\\[.*.\\]";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
System.out.println("Matcher? " + matcher.matches());
This return true if the text has a [
and ]
and false if it doesn't 如果文本带有
[
和]
,则返回true;否则,返回false。
Hope this can help you. 希望这可以帮到你。 Thanks.
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.