How can I split a string in Java and retain the delimiters?

后端 未结 6 1733
无人共我
无人共我 2020-12-06 17:01

I have this string (Java 1.5):

:alpha;beta:gamma;delta

I need to get an array:

{\":alpha\", \";beta\", \":gamma\", \";delta         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 17:32

    Assuming that you only have a finite set of seperators before the words in your string (eg ;, : etc) you can use the following technique. (apologies for any syntax errors, but its been a while since I used Java)

    String toSplit = ":alpha;beta:gamma;delta "
    toSplit = toSplit.replace(":", "~:")
    toSplit = toSplit.replace(";", "~;")
    //repeat for all you possible seperators
    String[] splitStrings = toSplit.split("~")
    

提交回复
热议问题