1. 概述
在Java中处理字符串时,经常需要清理数据,比如移除特定字符。移除括号字符就是常见需求之一。掌握正确方法后,这个操作其实很简单粗暴。
本文将探讨几种实现方式,并处理Unicode字符的复杂场景。
2. 问题定义
首先明确需求:哪些算括号字符?
在ASCII字符集中,有三对标准括号:
- 圆括号
( )
- 方括号
[ ]
- 花括号
{ }
实际开发中,尖括号 < >
也常被当作括号使用(如XML标签)。但严格来说,它们属于“小于/大于”符号。本文将它们视为第四对括号。
因此,我们的目标是从字符串中移除这四对字符。
测试用例:
static final String INPUT = "This (is) <a> [nice] {string}!";
期望结果:
"This is a nice string!"
⚠️ 注意:输入可能包含Unicode字符,后续会专门处理。
3. 使用StringUtils.replaceChars()方法
Apache Commons Lang 3是Java常用工具库,其StringUtils
类提供了丰富的字符串操作方法。
replaceChars()
方法可以批量替换字符,也能用于删除字符:
String result = StringUtils.replaceChars(INPUT, "(){}[]<>", null);
assertEquals("This is a nice string!", result);
✅ 关键点:当replaceChars
参数为null
时,该方法会删除searchChars
中指定的所有字符。
4. 基于正则的replaceAll()方法
正则表达式(Regex)是处理字符串模式的利器。Java标准库中的replaceAll()
方法结合正则可以高效移除括号:
String regex = "[(){}<>\\[\\]]";
String result = INPUT.replaceAll(regex, "");
assertEquals("This is a nice string!", result);
正则解析:
[...]
定义字符类()
、{}
、<>
在字符类中无需转义[
和]
需要转义为\\[
和\\]
,因为它们是字符类的边界符
⚠️ 踩坑提示:在字符类中,大部分特殊字符会失去特殊含义,但 [
和 ]
例外。
5. 处理Unicode括号字符
当字符串包含Unicode括号时(如数学符号⟨⟩
),需要特殊处理。测试用例:
static final String INPUT_WITH_UNICODE = "⟨T⟩❰h❱「i」⦇s⦈ (is) <a> [nice] {string}!";
其中包含的Unicode括号:
⟨⟩
(U+27E8/U+27E9) 数学尖括号❰❱
(U+2770/U+2771) 粗体尖括号「」
(U+300C/U+300D) 角括号⦇⦈
(U+2987/U+2988) 图像括号
✅ 解决方案:使用Unicode属性匹配
\p{Ps}
匹配所有开括号\p{Pe}
匹配所有闭括号
String regex = "\\p{Ps}|\\p{Pe}";
String resultWithUnicode = INPUT_WITH_UNICODE.replaceAll(regex, "");
assertEquals("This is <a> nice string!", resultWithUnicode);
❌ 问题:ASCII的< >
未被移除,因为它们不属于Unicode括号类别。
✅ 修正方案:手动补充<>
字符类
String regex = "\\p{Ps}|\\p{Pe}|[<>]";
String result = INPUT.replaceAll(regex, "");
String resultWithUnicode = INPUT_WITH_UNICODE.replaceAll(regex, "");
assertEquals("This is a nice string!", result);
assertEquals("This is a nice string!", resultWithUnicode);
6. 总结
本文探讨了三种移除字符串中括号的方法:
- Apache Commons Lang:简单粗暴,适合已引入该库的项目
- 正则表达式:Java原生支持,灵活性强
- Unicode处理:结合
\p{Ps}
和\p{Pe}
解决国际化场景
完整示例代码见GitHub仓库。