Java:字符串拆分 [英] Java: String splitting

查看:114
本文介绍了Java:字符串拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

     Mr John Smith Dickson <john@yahoo.com>

我想将其拆分为三个部分:

I want to split it into three parts:

第1部分 - 先生b
第2部分 - John Smith Dickson

第3部分 - john@yahoo.com

1st part - Mr
2nd part - John Smith Dickson
3rd part - john@yahoo.com

我对如何实现这一点感到困惑,任何人都可以帮忙吗?

I'm confused with how I might go about accomplishing this, can anyone help?

以上名称只是样本,名称可能会有所不同,例如。 John,John Smith,John Smith Dickson

the above name is just sample, the name might be vary, eg. John, John Smith, John Smith Dickson

推荐答案

你应该使用正则表达式。您可以捕获第一个单词直到空白,然后接下来的三个单词用空格分隔,然后是尖括号中的东西。

You should use a regex. You can capture the first word up until whitespace, then the next three words separated by whitespace, then the thing in the angle brackets.

这个有用

(\w+)\s+(\w+\s+\w+\s+\w+)\s*<(.*)>

\ w表示任何单词字符。 +表示1或更多。 \s表示任何空格字符。 ()中的事物被捕获。你将在java代码中使用的正则表达式是

\w means any word character. The + means 1 or more. \s means any whitespace character. Things in () are captured. The regex you would use in java code is

(\\w+)\\s+(\\w+\\s+\\w+\\s+\\w+)\\s*<(.*)>

此处测试

 http://www.regexplanet.com/simple/index.html

note你可以用拆分做到这一点,但是只要你分裂,然后获得令牌,然后分割令牌,然后获得更多令牌,然后再次分裂,你做的事情太复杂了。正则表达式大大简化了事情。

note that you could do this with splits, but anytime you are splitting, then getting the tokens, then splitting tokens, then getting more tokens, then splitting again, you are doing something too complicated. Regex greatly simplifies things.

这篇关于Java:字符串拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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