我有一个字符串:
String test = "firstName:a,lastName:b,addressOne:line 1,line 2,city:other";
我正在尝试test.replaceAll(",","\",\"")
。我的意思是替换,用","。我想这只是为了整个字符串。例如,addressOne是一个单独的字符串,逗号分隔,我不想替换它。有没有正则表达式或其他方式我可以做到这一点?
我应该得到像
"firstName":"a","lastName":"b","addressOne":"line 1 , line 2","city":"other"
after replace , but i am getting
"firstName":"a","lastName":"b","addressOne":"line 1 "," line 2","city":"other".
答案 0 :(得分:2)
您可以使用逗号分隔字符串,后跟一个后跟:
的单词。为了达到这个目的,您可以使用positive look-ahead并匹配前导词使用否定字符类[^:,]+
,它将匹配除:
和,
之外的任何字符串:
test.split(",(?=[^:,]+:)")