regex - .WithTransparentBounds 是什么?

标签 regex swift foundation nsregularexpression

我需要将多个空格折叠成一个空格。在 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 的实际含义,因为有一天我可能需要它?

提前致谢!

最佳答案

引用 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

关于regex - .WithTransparentBounds 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37605358/

相关文章:

regex - % :s/\([0-9]*\)_\(*\)/\2 will not rename files

ios - 如何解析 didReceiveUserInfo userInfo 参数?一个 __NSSingleObjectArrayI

ios - 如何在接受 Any 的函数上添加 OR 泛型类型约束

ios - 如何扩展 Swift Dictionary 类型以返回非空 String 或 nil

ios - 无法保存到 iOS 7.0.2 上的 NSUserDefaults

javascript - Ace编辑器如何向后查找?

正则表达式 - 阿曼手机号码

php - 如何使用 preg_replace 去除过多的单个空格

ios - 如何在 viewWillTransitionToSize 之后获取 subview 的大小

ios - 在 Swift 中将字符串转换为 HTML