简体   繁体   English

在 Java 中用特殊字符拆分字符串

[英]Split String with special characters in Java

I have a String with many commas for example:我有一个带有许多逗号的字符串,例如:

1,2,3,4,5,"one, two", 6, 7, "three, four", 8, 9

I want to split this string by comma(,) but parts with quotes shouldn't be splitted.我想用逗号 (,) 分割这个字符串,但是带引号的部分不应该被分割。 Is there a simple way to do this or should I prepare this string for example replace comma with something else:有没有一种简单的方法可以做到这一点,或者我应该准备这个字符串,例如用其他东西替换逗号:

1,2,3,4,5,"one#COMMA# two", 6, 7, "three#COMMA# four", 8, 9

and then split by comma(,)然后用逗号(,)分割

You can split by , followed by an optional blank characters \s* with a negative lookahead.您可以按,后跟一个可选的空白字符\s*进行拆分,并进行否定预测。 This Regex would identify the commas qualified to split the input String.此正则表达式将识别有资格拆分输入字符串的逗号。

,(?![^,]+"\s*,)\s*

The explanation is below and the demo is here: https://regex101.com/r/ghNMVo/1 :解释如下,演示在这里: https://regex101.com/r/ghNMVo/1

  • , is a comma literally ,字面意思是逗号
  • (?,[^,]+"\s*,) is a negative lookahead that matches if the following characters listed between (?! ... ) are not found right after the comma ( , ). This basically identifies the end of a String followed by the comma (ex. ...four", ) which means, the previous comma is not matched for split as long as a String follows. (?,[^,]+"\s*,)是一个否定前瞻,如果在(?! ... )之间列出的以下字符在逗号 ( , ) 之后没有找到,则匹配。这基本上标识了结束一个 String 后跟逗号(例如...four", ),这意味着,只要后面跟着一个 String,前面的逗号就不会匹配拆分。
    • [^,]+ at least one character except for the comma itself [^,]+至少一个字符,逗号本身除外
    • " followed by the " matched literally "后跟"字面匹配
    • \s* any number of blank characters \s*任意数量的空白字符
    • , followed by the , matched literally ,后跟,字面匹配
  • \s* are optional blank characters \s*是可选的空白字符

When applied to Java, don't forget to escape the characters.应用于Java时,不要忘记对字符进行转义。

final String string = "1,2,3,4,5,\"one, two\", 6, 7, \"three, four\", 8, 9";
final String[] array = string.split(",(?![^,]+\"\\s*,)\\s*");
Arrays.asList(array).forEach(System.out::println);
 1 2 3 4 5 "one, two" 6 7 "three, four" 8 9

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

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