如何使用任何空格字符作为分隔符分割字符串 [英] How to split a string with any whitespace chars as delimiters

查看:645
本文介绍了如何使用任何空格字符作为分隔符分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用所有空白字符(' ''\t''\n'等)作为分隔符,需要哪种正则表达式传递给java.lang.String.split()将字符串拆分为子字符串数组?

What regex pattern would need I to pass to java.lang.String.split() to split a String into an Array of substrings using all whitespace characters (' ', '\t', '\n', etc.) as delimiters?

推荐答案

以下内容

myString.split("\\s+");

这会将所有空白分组为定界符.

This groups all white spaces as a delimiter.

所以,如果我有字符串:

So if I have the string:

"Hello[space][tab]World"

这将产生字符串"Hello""World",并省略[space][tab]之间的空白.

This should yield the strings "Hello" and "World" and omit the empty space between the [space] and the [tab].

正如VonC所指出的那样,应该转义反斜线,因为Java首先会尝试将字符串转义为特殊字符,然后发送那个进行解析.您想要的是文字"\s",这意味着您需要传递"\\s".可能会造成一些混乱.

As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send that to be parsed. What you want, is the literal "\s", which means, you need to pass "\\s". It can get a bit confusing.

\\s等同于[ \\t\\n\\x0B\\f\\r].

这篇关于如何使用任何空格字符作为分隔符分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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