2013-04-30 79 views
2

我想在java中使用它的令牌拆分字符串。例如: ;字符串令牌化

String s = "A#B^C&D!ased&[email protected]%" 
String temp[] = s.split("[#^&[email protected]%]+"); 

Current output :- 
temp[0] = A 
temp[1] = B 
temp[2] = C 
temp[3] = D 
temp[4] = ased 

output which i want :- 
temp[0] = A# 
temp[1] = B^ 
temp[2] = C& 
temp[3] = D! 
temp[4] = ased& 

My current approach of doing is 
    pos = find the index of the token in string 
    pos = add the size of the token in pos 
    charAtPos = getcharfrom string at index pos 
    token = token + charAtPos 

如果你有什麼更好的辦法可以提示。我認爲這種方法在非常大的字符串上效率不高。

回答

0

分割方法分割周圍的正則表達式的匹配,所以也許它應該是[#|^|&|!|@|%]

+0

但它在我的情況下工作正常。它按預期返回結果,但我想要帶有分隔符的令牌 – 2013-04-30 13:27:33

1

String#split()使用正則表達式找到分割位置,並從結果中去除匹配組(這些記號,你通常不需要)。如果您還想獲取令牌,則需要使用 預讀 後視,進行零長度匹配。

String s = "A#B^C&D!ased&[email protected]%" 
String temp[] = s.split("(?<=[#^&[email protected]%]+)"); 

表達被改變爲每一個位置令牌匹配後並創建一個零長度匹配。因此結果也包含令牌。

1

如果您必須處理非常大的字符串,那麼您最好是推出自己的代碼。 Java模式匹配引擎是一個很好的通用工具,但通常可以通過自定義代碼來執行。

關鍵是使用類似Apache Commons的StringUtils庫。這非常易於使用,並且具有標準Java詞彙表中缺少的大量函數。

功能:

i = StringUtils.indexOfAny("A#B^C&D!ased&[email protected]%","[#^&[email protected]%]+"); 

將讓你的第一個分隔符的索引。您需要切掉前端並遍歷數組。