2013-04-30 67 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]%]+"); 

将让你的第一个分隔符的索引。您需要切掉前端并遍历数组。