Java Regex - Split string on spaces - Ignore spaces in quotes and escaped quotes [duplicate]

隐身守侯 提交于 2019-12-31 05:18:07

问题


I'm looking for regex to do the following in Java:

String originalString = "";
String splitString[] = originalString.spilt(regex);

Some test cases:

Original1: foo bar "simple"
Spilt1: { "foo", "bar", "\"simple\"" }

Original2: foo bar "harder \"case"
Spilt2: { "foo", "bar", "\"harder \"case\"" }

Original3: foo bar "harder case\\"
Spilt3: { "foo", "bar", "\"harder case\\"" }

Some snippets I have come across:

# Does not react to escaped quotes
 (?=([^\"]*\"[^\"]*\")*[^\"]*$)
# Finds relevant quotes that surround args
(?<!\\)(?:\\{2})*\"

Thanks!


回答1:


String stringToSplit = This is the string to split;

String[] split = stringToSplit.split("character to split at");

In this case, split[0] would result as ' This ', split[1] would be ' is ', split[2] would be ' the ', split[3] ' string ' split[4] ' to ' split[5] ' split '.

At this point you can do

var0 = split[0];
var1 = split[1];
var2 = split[2];

Where var0 would equal "This" And so on...

Hope this helps.




回答2:


Regex like this will work for simple cases:

("(.+?)(?<![^\\]\\)")|\S+

But I would not suggest to use RegEx for this task, but take a look at CSV parsers instead.



来源:https://stackoverflow.com/questions/37082706/java-regex-split-string-on-spaces-ignore-spaces-in-quotes-and-escaped-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!