Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

java - 如何使用任何空白字符分隔字符串来分隔符?(How do I split a string with any whitespace chars as delimiters?)

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

  ask by mcjabberz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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] .

(这将产生字符串"Hello""World"并省略[space][tab]之间的[space] 。)

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.

(正如VonC指出的那样,应该转义反斜杠,因为Java首先会尝试将字符串转义为特殊字符,然后将发送给解析。)

What you want, is the literal "\s" , which means, you need to pass "\\s" .

(您想要的是文字"\s" ,这意味着您需要传递"\\s" 。)

It can get a bit confusing.

(可能会造成一些混乱。)

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

(\\s等效于[ \\t\\n\\x0B\\f\\r])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...