如何将带有任何空格字符的字符串拆分为分隔符? [英] How do I split a string with any whitespace chars as delimiters?

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

问题描述

我需要使用什么正则表达式模式传递给 java.lang.String.split()方法,以使用所有空格字符将String拆分为子串数组( '','\ t','\ n'等等)作为分隔符?

解决方案

行中的东西of

  myString.split(\\\\ +); 

这会将所有空格分组为分隔符。



所以如果我有字符串:



Hello [space] [tab] ]世界



这应该产生字符串HelloWorld并省略 [space] [tab]



正如VonC指出的那样,反斜杠应该被转义,因为Java会首先尝试将字符串转义为特殊字符,并发送那个要解析。你想要的是文字\ s,这意味着你需要传递\\\\。它可能会有点混乱。



\\\\ 相当于 [\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

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

解决方案

Something in the lines of

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

This groups all white spaces as a delimiter.

So if I have the string:

"Hello[space][tab]World"

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

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.

The \\s is equivalent to [ \\t\\n\\x0B\\f\\r]

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

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