複数の空白を折りたたむ必要がある1つのスペースに。 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が実際に何を意味するのかを知りたいです。いつか必要になるかもしれません。
前もって感謝します!
回答:
回答№1は2NSRegularExpression.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