21
15

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.

Swift3で正規表現を楽に扱う

Last updated at Posted at 2016-10-21

はじめに

Swiftでは正規表現がかなり扱いにくいです。

その扱いにくさを克服するコードをいろいろな人が書いていますが、個人的にはどれもしっくりこなかったので、自分でも作りました。

gistで公開しています。
Regex.swift

使い方

ファイルごとプロジェクトに追加するだけで使えます。

let regex = try! Regex("([0-9]+?)月([0-9]+?)日")

// 最初のマッチ
let target = "10月3日12月25日1月1日"
if let match = regex.firstMatch(target) {
    print(match.wholeString) // マッチしたすべての範囲
    print(match.groups) // ()で囲まれた中身
} else {
    // どこにもマッチしないときにはnil
}



// すべてのマッチ
for match in regex.matches(target) {
    print(match.wholeString, match.groups)
}

// 置換
print(target.replace(regex, template: "xx月xx日"))

10月3日
["10", "3"]
10月3日 ["10", "3"]
12月25日 ["12", "25"]
1月1日 ["1", "1"]
xx月xx日xx月xx日xx月xx日

Matchオブジェクト

struct Match {
    var wholeString: String
    var groups: [String]
}

自作で申し訳ないですが、探索に対して、上のようなMatch構造体が返却されます。

wholeString はマッチした範囲の文字列全体が、 groups には、正規表現の中の () で囲われた部分が順に格納されます。

pythonのreモジュールでの、groups(0)がwholeString、groups(1)以降がgroupsに当たります。

実装

短いので、コードを読んでいただけると!

オプション

引数でrange(探索範囲)やoptionを指定することもできます(デフォルト値を空に設定しているだけです)

21
15
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
21
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?