2016-02-17 52 views
0

我試圖解析以下格式的字符串中的Java:解析字符串輸入的自由文本

Number-Action-Msg, Number-Action-Msg, Number-Action-Msg, Number-Action-Msg, ... 

例如

"512-WARN-Cannot update the name.,615-PREVENT-The app is currently down, please try again later.,736-PREVENT-Testing," 

我想獲得與數組以下條目:

512-WARN-Cannot update the name. 
615-PREVENT-The app is currently down, please try again later. 
736-PREVENT-Testing 

問題是,該消息是用戶輸入,所以我不能依靠只是逗號來分裂你字符串。這些行爲將始終是WARN或PREVENT。什麼是完成這個解析的最好方法?謝謝!

+1

@pczeus as told me .... *我不能只依賴逗號來分割字符串*所以......用逗號分隔...... :) –

回答

3

而不是分裂的逗號,你可以使用這個前瞻基於正則表達式匹配:

(\d+-(?:WARN|PREVENT).*?)(?=,\d+-(?:WARN|PREVENT)|,$) 

RegEx Demo

(?=,\d+-(?:WARN|PREVENT)|,$)是一個肯定的前瞻,斷言有一個逗號,然後是digits-(WARN|PREVENT)或行末。

+1

sweeeeeet ...遠處更多比我的優雅;) –

3

似乎相當簡單:

正則表達式:

WARN|PREVENT 

Regular expression visualization

Debuggex Demo

在java中:

String string = "512-WARN-Cannot update the name.,615-PREVENT-The app is currently down, please try again later.,736-PREVENT-Testing,"; 
String regex = "WARN|PREVENT"; 

System.out.println(Arrays.toString(string.split(regex))); 

將輸出:

[512-, -Cannot update the name.,615-, -The app is currently down, please try again later.,736-, -Testing,] 

當然,你可能需要調整正則表達式添加-,例如:

String regex = "-WARN-|-PREVENT-";