1

我有一个自定义传输格式,它以以下格式打包数据

[a:000,"名称","字段","字段","字段"]

我正在尝试将各个行拆分出来以获取左括号之后的第一个字符和所有 CSV 值。a、000、“名称”、“字段”、“字段”等...

我拼凑起来

[^?,:\[\]]

这会将所有单个字符拆分出来,而不是冒号/逗号分隔的字段。我知道这不会在引号内容纳逗号。所以这显然是垃圾!

嵌入式逗号并不是一个真正的大问题,因为我们控制着两端的数据,所以我可以逃避它们。

感谢您的任何见解!

4

2 回答 2

2

与其尝试拆分多个字符并忽略其中一些,不如尝试匹配您想要匹配的任何内容。由于您没有指定实现语言,因此我将其发布为 Perl,但您可以将其应用于任何支持后向和前瞻的风格。

while ($subject =~ m/(\w+(?=:)|(?<=:)\d+|(?<=,")[^"]*?(?="))/g) {
    # matched text = $&
}

解释:

# (\w+(?=:)|(?<=:)\d+|(?<=,")[^"]*?(?="))
# 
# Match the regular expression below and capture its match into backreference number 1 «(\w+(?=:)|(?<=:)\d+|(?<=,")[^"]*?(?="))»
# Match either the regular expression below (attempting the next alternative only if this one fails) «\w+(?=:)»
# Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=:)»
# Match the character “:” literally «:»
# Or match regular expression number 2 below (attempting the next alternative only if this one fails) «(?<=:)\d+»
# Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=:)»
# Match the character “:” literally «:»
# Match a single digit 0..9 «\d+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Or match regular expression number 3 below (the entire group fails if this one fails to match) «(?<=,")[^"]*?(?=")»
# Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=,")»
# Match the characters “,"” literally «,"»
# Match any character that is NOT a “"” «[^"]*?»
# Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=")»
# Match the character “"” literally «"»

看到它工作

于 2012-08-15T20:50:35.720 回答
0

您当然可以通过正则表达式来做到这一点,但合适的工具很可能是 CSV 解析器。你可以试试 Dave DeLong 为 Objective C 编写的这个:

https://github.com/davedelong/CHCSVParser

于 2014-11-26T17:15:16.110 回答