java - 使用特殊字符拆分字符串并保留它们
问题描述
我正在尝试使用特殊字符拆分字符串,但无法正确拆分括号。这是我正在尝试的代码:
class Ione
{
public static void main (String[] args) throws java.lang.Exception
{
String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = str.split(",\\s+|(?=\\W)");
for(int q=0; q<chunks.length; q++) {
System.out.println(""+chunks[q]);
}
}
}
正则表达式不拆分起始括号(
我正在尝试获得以下输出:
g,i,+,w,+,|,(,d,|,(,u,+,f,),),+
有人可以帮助我。谢谢你。
解决方案
所以你想用来split()
分别获取每个字符,除了空格和逗号,所以用空格/逗号和“无”分割,即非空格/逗号字符之间的零宽度“空格”。
String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = str.split("[\\s,]+|(?<![\\s,])(?![\\s,])");
System.out.println(String.join(",", chunks));
输出
g,i,+,w,+,|,(,d,|,(,u,+,f,),),+
替代方案:搜索您想要的内容,并将其收集到一个数组中或List
(需要 Java 9):
String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = Pattern.compile("[^\\s,]").matcher(str).results()
.map(MatchResult::group).toArray(String[]::new);
System.out.println(String.join(",", chunks));
相同的输出。
对于旧版本的 Java,请使用find()
循环:
String str = "g, i+, w+ | (d | (u+, f))+";
List<String> chunkList = new ArrayList<>();
for (Matcher m = Pattern.compile("[^\\s,]").matcher(str); m.find(); )
chunkList.add(m.group());
System.out.println(chunkList);
输出
[g, i, +, w, +, |, (, d, |, (, u, +, f, ), ), +]
您始终可以将 转换List
为数组:
String[] chunks = chunkList.toArray(new String[0]);
推荐阅读
- docker - 码头工人群。如何从管理节点连接到在工作节点上运行的容器?
- node.js - 我在哪里可以找到 firebase-debug.log 来了解为什么模拟器没有完全关闭?
- javascript - 我需要 Vue.set() 来更改数据对象的值吗?
- python - 属性错误:模块“rasa_nlu.utils”没有属性“list_files”
- javascript - 在 redux-saga 中发送两个请求(调用两个函数)
- react-native - 我怎样才能得到一个有点相似的图表?
- firebase - 无法在 Firebase 托管中加载 language.json 和 css 文件
- python - 如何将字符串类型的 Pandas Dataframe 列转换为 JSON 中的 SET
- reactjs - React Native 中的缺口角矩形
- rust - 链接自定义动态库 Rust 时出错