正则表达式用嵌套引号解析csv

前端之家收集整理的这篇文章主要介绍了正则表达式用嵌套引号解析csv前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Possible Duplicate:
07000
07001

我知道这个问题已经问了很多次,但有不同的答案;我很困惑.

我的行是:

  1. 1,3.2,BCD,"qwer 47"" ""dfg""",1

可选的引用和双引号MS Excel标准. (数据:qwer 47“”dfg“表示如下”qwer 47“”“”dfg“”“.)

我需要一个正则表达式.

好的,你从评论中看到正则表达式不是正确的工具.但如果你坚持,这里有:

这个正则表达式将在Java(或.NET和其他支持占有量词和冗长正则表达式的实现)中工作:

  1. ^ # Start of string
  2. (?: # Match the following:
  3. (?: # Either match
  4. [^",\n]*+ # 0 or more characters except comma,quote or newline
  5. | # or
  6. " # an opening quote
  7. (?: # followed by either
  8. [^"]*+ # 0 or more non-quote characters
  9. | # or
  10. "" # an escaped quote ("")
  11. )* # any number of times
  12. " # followed by a closing quote
  13. ) # End of alternation,# Match a comma (separating the CSV columns)
  14. )* # Do this zero or more times.
  15. (?: # Then match
  16. (?: # using the same rules as above
  17. [^",\n]*+ # an unquoted CSV field
  18. | # or a quoted CSV field
  19. "(?:[^"]*+|"")*"
  20. ) # End of alternation
  21. ) # End of non-capturing group
  22. $ # End of string

Java代码

  1. boolean foundMatch = subjectString.matches(
  2. "(?x)^ # Start of string\n" +
  3. "(?: # Match the following:\n" +
  4. " (?: # Either match\n" +
  5. " [^\",\\n]*+ # 0 or more characters except comma,quote or newline\n" +
  6. " | # or\n" +
  7. " \" # an opening quote\n" +
  8. " (?: # followed by either\n" +
  9. " [^\"]*+ # 0 or more non-quote characters\n" +
  10. " | # or\n" +
  11. " \"\" # an escaped quote (\"\")\n" +
  12. " )* # any number of times\n" +
  13. " \" # followed by a closing quote\n" +
  14. " ) # End of alternation\n" +
  15. ",# Match a comma (separating the CSV columns)\n" +
  16. ")* # Do this zero or more times.\n" +
  17. "(?: # Then match\n" +
  18. " (?: # using the same rules as above\n" +
  19. " [^\",\\n]*+ # an unquoted CSV field\n" +
  20. " | # or a quoted CSV field\n" +
  21. " \"(?:[^\"]*+|\"\")*\"\n" +
  22. " ) # End of alternation\n" +
  23. ") # End of non-capturing group\n" +
  24. "$ # End of string");

请注意,您不能假设CSV文件中的每一行都是完整的行.您可以在CSV行中包含换行符(只要包含换行符的列用引号括起来).这个正则表达式知道这一点,但如果你只给它一个部分行,它就会失败.这是您真正需要CSV解析器来验证CSV文件的另一个原因.这就是解析器的作用.如果您控制输入并且知道在CSV字段中永远不会有换行符,那么您可能会放弃它,但只有这样.

猜你在找的正则表达式相关文章