简而言之:
给定以下字符串:
输入字符串 -> "hello, world", oh my, parapappa12
我想提取这三个“ token ”:
输出 token ->
- “你好,世界”
- 我的天啊
- parapappa12
在 ios 中标记字符串
我得到了一个包含一些数据的文件。它看起来像:
word , word, word
word , word, word
word , word, word
有些单词可以包含“,”,但前提是单词以特定字符开头和结尾,例如。以“开始,以”结束
单词示例:
word : blebla bla bla
word : "bla bla bla, bla"
我如何定义一个正则表达式来根据“,”忽略单词之间的空格并包括这种“特殊”情况来标记文件?
我记得在 Perl 中使用正则表达式来实现类似的东西,但那是很久以前的事了,我有点忘记了语法,我不确定 Objective-C 和 iOS 是否支持它
最佳答案
首先,一个 Perl 单行代码(这里是 fullscreen):
# echo -n '"hello, world" , oh my, parapappa12' | perl -ne 'print "<$1>\n" while /("[^"]*"|[^, ]+)/g'
<"hello, world">
<oh>
<my>
<parapappa12>
NSString* const str = @"\"hello, world\" , oh my, parapappa12";
[self splitCommas:str];
- (void)splitCommas:(NSString*)str
{
NSString* const pattern = @"(\"[^\"]*\"|[^, ]+)";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern
options:0
error:nil];
NSRange searchRange = NSMakeRange(0, [str length]);
NSArray *matches = [regex matchesInString:str
options:0
range:searchRange];
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
NSLog(@"%@", [str substringWithRange:matchRange]);
}
}
正则表达式的解释:
- 您可以搜索“带引号的字符串”:
"[^"]*"
(除引号外的任何内容) - 或者您捕获逗号之间的任何内容:
[^, ]+
(逗号或空格除外)
(方括号定义“字符类”,插入符号表示否定)。
注意:我的解决方案不会像 "I say\"Hello\""
关于ios - 使用正则表达式在 ios 中标记字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23610329/