我需要将多个空格折叠到一个空格中。在使用Foundation Framework NSString Class Reference,Google和stackoverflow之后,我找到了足够的信息和示例代码来帮助我
var myString = "Snoopy Doogitz"
if let regex = try? NSRegularExpression( pattern: "\\s+", options: [] ) {
let modString = regex.stringByReplacingMatchesInString( myString, options: .WithTransparentBounds, range: NSMakeRange( 0, myString.characters.count ), withTemplate: " ")
print( modString )
}
哪个有效。
但是,我似乎无法在.WithTransparentBounds
的文档中找到解释如果我从我的代码中删除它
var myString = "Snoopy Doogitz"
if let regex = try? NSRegularExpression( pattern: "\\s+", options: [] ) {
let modString = regex.stringByReplacingMatchesInString( myString, options: [], range: NSMakeRange( 0, myString.characters.count ), withTemplate: " ")
print( modString )
}
这也很好。但在我离开之前,我很想知道选项是什么.WithTransparentBounds实际上意味着,有一天我可能需要它吗?
提前致谢!
答案 0 :(得分:2)
引用NSRegularExpression.h中的注释:
NSMatchingAnchored
,NSMatchingWithTransparentBounds
和NSMatchingWithoutAnchoringBounds
可以应用于任何匹配或替换方法。如果指定NSMatchingAnchored
,则匹配仅限于搜索范围开头的匹配。 如果指定了NSMatchingWithTransparentBounds
,匹配可以检查超出搜索范围界限的字符串部分,用于字边界检测,超前等等。如果NSMatchingWithoutAnchoringBounds
是指定的^
和$
不会自动匹配搜索范围的开头和结尾(但仍会匹配整个字符串的开头和结尾)。如果搜索范围涵盖整个字符串,则NSMatchingWithTransparentBounds
和NSMatchingWithoutAnchoringBounds
无效。
这是一个示例,说明了包含WithTransparentBounds时的区别:
let str = "foobarbaz"
let re = try! NSRegularExpression(pattern: "bar\\b", options: [])
re.numberOfMatchesInString(str, options: .WithTransparentBounds, range: NSRange(location: 0, length: 9)) // returns 0
re.numberOfMatchesInString(str, options: .WithTransparentBounds, range: NSRange(location: 3, length: 3)) // returns 0
re.numberOfMatchesInString(str, options: [], range: NSRange(location: 3, length: 3)) // returns 1