【发布时间】:2018-06-08 15:39:56
【问题描述】:
上下文是一个 IOS 应用程序。 我想替换用括号括起来的空格。
例如:
托托“是比尔”应该变成 托托“是#Bill”
天气“晴朗”应该变成 天气“晴朗#and#clear”
我已经根据另一个代码使用以下代码进行了试验 post
NSString *pattern = @"(?:(?<=^\")(\\s+))|(?:(?!^\")(\\s+)(?=.))|(?:(\\s+)(?=\"$))"; // (?:(?<=^")(\s+))|(?:(?!^")(\s+)(?=.))|(?:(\s+)(?="$))
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"#"];
NSLog(@"modified %@", modifiedString);
但这不正常。
所有空格都被替换(Toto#"is#Bill")
我只用 (?:(?!^")(\s+)(?=.)) 得到相同的结果
我自己做了一个 (?:\"\S*)(\s)(?:\S*) 也不行
我会很感激这方面的帮助! 谢谢
【问题讨论】:
-
你不能用普通的正则表达式和字符串替换模式来做到这一点,因为起始和尾随分隔符是相等的。您需要一个回调来替换双引号子字符串中的所有空格,唯一缺少的是您的字符串是否可以包含转义序列,或者它们是否可以仅与
"[^"]+"模式匹配。 -
我的字符串是搜索文本框的字符串。它们不会包含转义序列。
-
对于这么简单的事情,这看起来有点矫枉过正,但好的,我会试试这个。thx
-
对不起,那是 Objective-C。在 Python 中,它只是一个
re.sub(r'"[^"]+"', lambda x: x.group().replace(' ', '#'), s)。在 C# 中,Regex.Replace(s, "\"[^\"]+\"", m => m.Value.Replace(" ", "#"))。 JS:s.replace(/"[^"]+"/g, function(m) {return m.replace(/\s/g, '#');})
标签: regex replace nsstring space quotes