简体   繁体   English

拆分引用了一个字符串java

[英]Split quoted of a string java

I would like some help with the following question. 我想对以下问题提供一些帮助。

I have the following string 我有以下字符串

1,1,0,3, '2014-12-02 12:15:13', '2015-05-20', 'string', 'other string', 1,2,1, NULL, '', '', NULL, NULL, NULL

and would make the split and put in an array only those quoted ignoring others. 并且会进行拆分并将数组只放入引用忽略其他数组的数组中。 You could even separate by commas, but the sequences vary. 你甚至可以用逗号分隔,但序列各不相同。

I am using the following regex: 我使用以下正则表达式:

 String splitStr[] = str.split("\'([^\\']*)\'");

but the output is as follows: 但输出如下:

1,1,0,3,, ,,,, ,,, 1,2,1, NULL,, ,,, NULL, NULL, NULL

What I need is exactly the opposite, something like this: 我需要的恰恰相反,如下所示:

'2014-12-02 12:15:13', '2015-05-20', 'string', 'other string','', ''

You can do this in Java: 你可以用Java做到这一点:

String str = str = "1,1,0,3, '2014-12-02 12:15:13', '2015-05-\\'20', 'string', 'other string', 1,2,1, NULL, '', '', NULL, NULL, NULL";
Pattern p = Pattern.compile("'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'");
Matcher m = p.matcher(str);

while (m.find()) {
    System.out.println("val: [" + m.group(1) + ']');
}

RegEx Demo RegEx演示

Output: 输出:

val: [2014-12-02 12:15:13]
val: [2015-05-\'20]
val: [string]
val: [other string]
val: []
val: []

Regex doesn't support state, so it's basically impossible to do this as a general case. 正则表达式不支持状态,因此基本上不可能将此作为一般情况。 You can't "count" how many quote marks you've seen in regex. 你无法“计算”你在正则表达式中看到过多少引号。

You can find libraries to do things like this or loop through the String and split it either matching it yourself or using a pattern matcher. 您可以找到库来执行此类操作或循环遍历String并将其拆分为自己匹配或使用模式匹配器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM