![](/img/trans.png)
[英]Regex to return the characters between square brackets (but not the brackets)
[英]How to divide a string with a regex through characters that are outside square brackets?
我有这个字符串:
PARTNER6;PARTNER7[PORTAL4;PORTAL5];PARTNER1[PARTNER1WEB] -> ∞
我想这样划分:
PARTNER6
PARTNER7[PORTAL4;PORTAL5]
PARTNER1[PARTNER1WEB]
我尝试使用这个表达式,但它划分了所有内容,包括括号中的内容
[\s,;]+
我不知道如何只划分括号外的内容
您可以使用此正则表达式来获取所有匹配项:
\w+(?:\[[^]]*\]\w*)*\w*
正则表达式详细信息:
\w+
:匹配 1+ 个单词字符(?:\[[^]]*\]\w*)*
:匹配[...]
字符串后跟 0 个或多个单词字符。 重复此组 0 次或多次\w*
:匹配0个或多个单词字符代码:
jshell> String regex = "\\w+(?:\\[[^]]*\\]\\w*)*\\w*";
regex ==> "\\w+(?:\\[[^]]*\\]\\w*)*\\w*"
jshell> String string = "PARTNER6;PARTNER7[PORTAL4;PORTAL5];PARTNER1[PARTNER1WEB] -> ∞";
string ==> "PARTNER6;PARTNER7[PORTAL4;PORTAL5];PARTNER1[PARTNER1WEB] -> ∞"
jshell> Pattern.compile(regex).matcher(string).results().map(MatchResult::group).collect(Collectors.toList());
$3 ==> [PARTNER6, PARTNER7[PORTAL4;PORTAL5], PARTNER1[PARTNER1WEB]]
我会在这里使用正则表达式查找所有方法:
String input = "PARTNER6;PARTNER7[PORTAL4;PORTAL5];PARTNER1[PARTNER1WEB]";
String pattern = "(\\w+(?:\\[.*?\\])?);?";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
System.out.println(m.group(1));
}
这打印:
PARTNER6
PARTNER7[PORTAL4;PORTAL5]
PARTNER1[PARTNER1WEB]
上面使用的正则表达式模式匹配带有\w+
的单词,后跟方括号中的可选术语,再后跟可选的分号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.