我需要将多个空格折叠成一个空格。在 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
, andNSMatchingWithoutAnchoringBounds
can apply to any match or replace method. IfNSMatchingAnchored
is specified, matches are limited to those at the start of the search range. IfNSMatchingWithTransparentBounds
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. IfNSMatchingWithoutAnchoringBounds
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
andNSMatchingWithoutAnchoringBounds
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/