我遇到了这个表达式,并试图弄清楚正则表达式会匹配什么?
new Text(Arrays.toString(parts).replaceAll("^\\[|\\]$", "")
我使用Xeger生成一些字符串,但它可能没有显示正确的字符串,因为它只生成2个字符串^ [和] $
答案 0 :(得分:3)
您的正则表达式的作用是匹配起始[
和结尾]
<强> Working demo 强>
regex101的解释:
1st Alternative: ^\[
^ assert position at start of a line
\[ matches the character [ literally
2nd Alternative: \]$
\] matches the character ] literally
$ assert position at end of a line
所以,这段代码:
"[sdfsad sdfsd]asdfas]".replaceAll("^\\[|\\]$", "")
将删除开头和结尾[
]
,结果字符串为:
sdfsad sdfsd]asdfas