拆分 NSString 保留带引号的子字符串
我需要拆分一个用逗号分隔的字符串,同时保留任何带引号的子字符串(也可能有逗号)。
字符串示例:
NSString *str = @"One,Two,\"This is part three, I think\",Four";
for (id item in [str componentsSeparatedByString:@","])
NSLog(@"%@", item);
这返回:
- 一二
- “
- 我认为这是第三部分
- 有
- 没有
合理
- 的
- 来
- 方法
- ”四正确的结果(尊重引用的子字符串)应该是:一二“我认为这是第三部分”四
做到这一点,没有重新发明或重写引号感知解析例程?
I need to split up a string which is separated by commas while preserving any quoted substrings (which may have commas too).
String example:
NSString *str = @"One,Two,\"This is part three, I think\",Four";
for (id item in [str componentsSeparatedByString:@","])
NSLog(@"%@", item);
This returns:
- One
- Two
- "This is part three
- I think"
- Four
The correct result (respecting quoted substrings) should be:
- One
- Two
- "This is part three, I think"
- Four
Is there a reasonable way to do this, without re-inventing or re-writing quote-aware parsing routines?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们换个方式来思考这个问题。您拥有的是一个以逗号分隔的字符串,并且您需要字符串中的字段。
有一些代码:
https://github.com/davedelong/CHCSVParser
你会这样做:
Let's think about this a different way. What you have is a comma-seperated string, and you want the fields in the string.
There's some code for that:
https://github.com/davedelong/CHCSVParser
And you'd do this:
这是同一问题的 C# 答案。
C# 正则表达式拆分 - 引号外的逗号
您可能可以在 Objective-C 中使用相同的正则表达式
NSString 拆分正则表达式
,(?=(?:[^']*'[^']*')*[^']*$)
Here is a C# answer to the same problem.
C# Regex Split - commas outside quotes
You could probably use the same Regex in Objective-C
NSString split Regex with
,(?=(?:[^']*'[^']*')*[^']*$)