[英]Java regex: split comma-separated values but ignore commas in quotes
I have text as follows: 我的文字如下:
"text","1","more, more text","3"
Could anyone kindly show me what regex delimeters I have to use to get the following: 任何人都可以告诉我我必须使用哪些正则表达式分度数才能获得以下结果:
text
1
more, more text
3
I was reading the Sun tutorial here , up until "Methods of the matcher class" but I am still at a loss. 我在这里阅读Sun教程,直到“ Matcher类的方法”为止,但我仍然茫然。 Thanks!
谢谢!
If it were something like text,1,more
it would be easy enough, but unfortunately it's not like that. 如果它是诸如
text,1,more
类的东西text,1,more
那么它会很容易,但是不幸的是并非如此。 Any ideas? 有任何想法吗?
Try this pattern: "(.+?)"
尝试以下模式:
"(.+?)"
It will match 1 or more characters between double quotes. 双引号之间将匹配1个或多个字符。 The part of the text between the quotes is available as
matcher.group(1)
. 引号之间的文本部分可以作为
matcher.group(1)
。
Look at the javadoc for Pattern
class to learn more. 查看
Pattern
类的javadoc了解更多信息。 Also, look at matcher.find()
method. 另外,请查看
matcher.find()
方法。
您可以尝试此[^\\"]+(?<!\\",?)
You can either go straight for the split() method like this: 您可以直接使用split()方法,如下所示:
String text = "\"text\",\"1\",\"more, more text\",\"3\"";
String[] split = text.split("\"(,\")?");
for (String string : split) {
System.out.println(string);
}
(beware that this returns a length 5 array, with the first position being an empty string) (请注意,这将返回一个长度为5的数组,第一个位置为空字符串)
Or, if you want to use a Pattern/Matcher, you can do it like this: 或者,如果您想使用模式/匹配器,可以这样做:
Pattern pattern = Pattern.compile("\"([^\"]+)\"");
Matcher matcher = pattern.matcher(text);
while(matcher.find()){
System.out.println(matcher.group(1));
}
你可以得到所有以一个开始部分"
并与另一完成"
,然后串各部分的第一个和最后一个字符。
You can try something like that. 您可以尝试类似的方法。 I know, it is not good solution, but it can help you :)
我知道,这不是一个好的解决方案,但可以为您提供帮助:)
string[] s=text.split("\",\"");
s[0]=s[0].substring(1);
s[s.length-1]=s[s.length-1].substring(0,s[s.length-1].length);
"[^"]*"
seems it is! 好像是! in java string you can use
在java字符串中可以使用
"\"[^\"]*\""
You can test it online here: http://www.regexplanet.com/simple/index.html 您可以在此处在线测试: http : //www.regexplanet.com/simple/index.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.