1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSRegularExpression の文字数

Last updated at Posted at 2019-05-13

正規表現 NSRegularExpression の場合、文字数は "文字列".utf16.count を利用しないといけない場合がありでした。

下記ソースコードでは絵文字を利用した場合、 "".count と "".utf16.count では文字数が異なり utf16 でないと文字数が少なくなりマッチしませんでした。

Swift5.0
import UIKit

func regExp(in: String, length: Int)
{
    do {
        let pattern = #"\{(.*?):(.*?)\}"#
        let regExp = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        let matches = regExp.matches(in: str, options: [], range: NSRange(location: 0, length: length))
        
        if matches.count == 0 {
            print("No matches")
            return
        }
        
        for match in matches {
            print("match.numberOfRanges:[\(match.numberOfRanges)]")
            
            for index in 0 ..< match.numberOfRanges {
                let nsRange = match.range(at: index)
                
                if let range = Range(nsRange, in: str) {
                    let value = str[range]
                    print("range[\(index)]:[\(nsRange)]:[\(value)]")
                }
            }
        }
    } catch {
        print("Error = \(error)")
    }
}

let str = "{Hello:😹playground}"

print("------------------------------")
print("str.count:[\(str.count)]")
regExp(in: str, length: str.count)
print("------------------------------")

print("------------------------------")
print("str.utf16.count:[\(str.utf16.count)]")
regExp(in: str, length: str.utf16.count)
print("------------------------------")

Output
------------------------------
str.count:[19]
No matches
------------------------------
------------------------------
str.utf16.count:[20]
match.numberOfRanges:[3]
range[0]:[{0, 20}]:[{Hello:😹playground}]
range[1]:[{1, 5}]:[Hello]
range[2]:[{7, 12}]:[😹playground]
------------------------------

いろいろと調べてみた結果 NSString が使われる場合は utf16 を使う必要がありそうです。
Apple Developer: NSString

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?