如何测试和解析字符串中的括号?
How to test & parse brackets from a String?
在平台 Discord 上,有所谓的嵌入。它们可以定制,我们需要一个命令来发送它们。
我们希望命令看起来像这样:!embed [此处用作标题] [此处用作说明] [以及颜色参数]
现在,我必须检查括号是否平衡,所以我可以确保继续阅读括号之间的内容。
您将如何检查然后获取括号中的文本?
我想到了这样的事情:
if(x % 2 == 0) { //Checking if x (number of opening and closing brackets) are equals (divisible by 2)
//Continue with sending the Embed
}
现在的问题是在我检查平衡括号之后,我将如何获得它们之间的文本?
有任何想法吗?
我想过检查括号后的每个字符和一个字符,我会开始将字符添加到字符串中,直到结束括号出现。
其他想法或更简单的方法?
提取括号之间字符串的最简单方法是使用正则表达式。
例如:
Pattern pattern = Pattern.compile("\[(.*?)]");
String x = "!embed [This here goes as a title] [This here goes as a description] [And an argument for Color]";
Matcher matcher = pattern.matcher(x);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
给出:
This here goes as a title
This here goes as a description
And an argument for Color
要检查括号,您可以使用 Stack,只要找到左括号,就将其压入堆栈。当您找到右括号时,您会从堆栈中弹出。
最后,如果栈为空则括号平衡。
在平台 Discord 上,有所谓的嵌入。它们可以定制,我们需要一个命令来发送它们。
我们希望命令看起来像这样:!embed [此处用作标题] [此处用作说明] [以及颜色参数]
现在,我必须检查括号是否平衡,所以我可以确保继续阅读括号之间的内容。 您将如何检查然后获取括号中的文本?
我想到了这样的事情:
if(x % 2 == 0) { //Checking if x (number of opening and closing brackets) are equals (divisible by 2)
//Continue with sending the Embed
}
现在的问题是在我检查平衡括号之后,我将如何获得它们之间的文本? 有任何想法吗? 我想过检查括号后的每个字符和一个字符,我会开始将字符添加到字符串中,直到结束括号出现。
其他想法或更简单的方法?
提取括号之间字符串的最简单方法是使用正则表达式。 例如:
Pattern pattern = Pattern.compile("\[(.*?)]");
String x = "!embed [This here goes as a title] [This here goes as a description] [And an argument for Color]";
Matcher matcher = pattern.matcher(x);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
给出:
This here goes as a title
This here goes as a description
And an argument for Color
要检查括号,您可以使用 Stack,只要找到左括号,就将其压入堆栈。当您找到右括号时,您会从堆栈中弹出。 最后,如果栈为空则括号平衡。