need to split sting based on :(colon) but not the colon which is enclosed in double Quotes

时间:2016-04-04 18:18:41

标签: java split colon

need to split string based on :(colon) but not the colon which is enclosed in double Quotes , for example abc":"ghi:123":"456, the split result should be like this, 1st part abc":"ghi, second part should be 123":"456. Java.

2 个答案:

答案 0 :(得分:1)

It's fairly simple, actually. You can learn more about regular expressions, the tool I'm using here, by Googling them or looking here.

The pattern you want is this:

(?<="):(?!")|(?<!"):(?=")|(?<!"):(?!")

This is made up of three almost-identical pieces; each piece's description is available in the link above. However, in short, they look for any colon with a single " on precisely one side, or a colon with no " around it at all.

You use it like this:

string.split("(?<=\"):(?!\")|(?<!\"):(?=\")|(?<!\"):(?!\")");

Notice that the " have become \" to escape it. If you don't put the backslashes, you'll get an error.

Online test here.

答案 1 :(得分:0)

You can use regex to match exactly ":" and not :

Using your string example abc":"ghi:123":"456 the regex [a-z0-9]{3}":"[a-z0-9]{3} will match abc":"ghi and 123":"456