How to split this string in java need regex?

时间:2016-04-15 15:06:43

标签: java regex string split

i need to split this string:

COMITATO: TRIESTE Indirizzo legale: VIA REVOLTELLA 39 34139 
Trieste (Trieste) Mob.: 3484503368 Fax: 040310096 Sito web: www.csentrieste.it/

the wanted result must be an array like:

{COMITATO:,TRIESTE,Indirizzo legale:,VIA REVOLTELLA 39 34139 
Trieste (Trieste) ,Mob.:,3484503368,Fax:,Sito web:,www.csentrieste.it/}

the problem is also that some attribute of string can be missing so i cant split using the header of attribute like "COMITATO:" or "Indirizzo legale:"

example:if "Indirizzo legale:" its missing string will appear like:

COMITATO: TRIESTE Mob.: 3484503368 Fax: 040310096 Sito web: www.csentrieste.it/

1 个答案:

答案 0 :(得分:1)

好吧,这个正则表达式将解析你给定的输入:

(?<firstname>.*?):\s*(?<lastname>\w+)(?:(?<occupation>[^:]+):\s*(?<address>.+\n.+))?\sMob.:\s*(?<mobile>\d+)\s*Fax:\s*(?<fax>\d+)\s*Sito web:\s*(?<website>.*)

我们可以通过使用命名组来挽救一些可读性并轻松访问结果。没有什么比正则表达式更聪明,我们只是爬过字符串,使用我们可以锚定模式的静态结构:冒号,“Mob”,“传真”和“Sito web”。显然,“可能缺少”的地址部分是可选的。

<强> regex demo here