.WithTransparentBounds 是什么?

What is .WithTransparentBounds?

我需要将多个白色space折叠成一个space。在 Foundation Framework NSString Class Reference、Google 和 Whosebug 中深入挖掘之后,我找到了足够的信息和示例代码来

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 的实际含义,因为有一天我可能需要它?

提前致谢!

引用NSRegularExpression.h中的评论:

NSMatchingAnchored, NSMatchingWithTransparentBounds, and NSMatchingWithoutAnchoringBounds can apply to any match or replace method. If NSMatchingAnchored is specified, matches are limited to those at the start of the search range. If NSMatchingWithTransparentBounds is specified, matching may examine parts of the string beyond the bounds of the search range, for purposes such as word boundary detection, lookahead, etc. If NSMatchingWithoutAnchoringBounds is specified, ^ and $ will not automatically match the beginning and end of the search range (but will still match the beginning and end of the entire string). NSMatchingWithTransparentBounds and NSMatchingWithoutAnchoringBounds have no effect if the search range covers the entire string.

下面的示例说明了包含 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