-3

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.

Haifeng Zhang
  • 27,283
  • 17
  • 68
  • 115
cecil
  • 3
  • 2
  • [This](http://stackoverflow.com/questions/4736/learning-regular-expressions) might help you out. – Nic Apr 04 '16 at 18:22
  • Please make sure to accept whichever answer was most helpful – scroll down to it and click the green check mark. – Nic Apr 05 '16 at 11:01

2 Answers2

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.

Community
  • 1
  • 1
Nic
  • 6,010
  • 8
  • 47
  • 67
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

scoots
  • 109
  • 5
  • This answer is accurate, but it seems less flexible than the other which totally isn't mine nope. Still, if the portions are all the same length and contain `":"`, then this works great; just replace `3` with whatever the right number is – Nic Apr 04 '16 at 18:38
  • @QPaysTaxes agreed. my answer was just meant as an example of how he could use regex to match for ":" vs just : based on the example of a string that the OP gave. My solution would only work if the given string OP is trying to match against follows his example, or something very close to the example's format. – scoots Apr 04 '16 at 18:42