Java string.split - 由多个字符分隔符组成 [英] Java string.split - by multiple character delimiter

查看:518
本文介绍了Java string.split - 由多个字符分隔符组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于所有可能的分隔符解析整个文件,如逗号,冒号,冒号,句号,空格,hipns等。

I would like to parse entire file based on all the possible delimiters like commas, colon, semi colons, periods, spaces, hiphens etcs.

假设我有一个假设的字符串行你好,X怎么样:你呢?我应该得到带有项目Hi,X,How,how,are,any和you的输出数组。

Suppose I have a hypothetical string line "Hi,X How-how are:any you?" I should get output array with items Hi,X,How,how,are,any and you.

如何在String.split方法中指定所有这些分隔符?

How do I specify all these delimiter in String.split method?

提前致谢。

推荐答案

String.split 采用正则表达式,在这种情况下,您需要非单词字符(正则表达式 \W )作为拆分,所以它只是:

String.split takes a regular expression, in this case, you want non-word characters (regex \W) to be the split, so it's simply:

String input = "Hi,X How-how are:any you?";
String[] parts = input.split("[\\W]");

如果你想更明确,你可以使用表达式中的确切字符:

If you wanted to be more explicit, you could use the exact characters in the expression:

String[] parts = input.split("[,\\s\\-:\\?]");

这篇关于Java string.split - 由多个字符分隔符组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆