PySwiftyRegex

Easily deal with Regex in Swift in a Pythonic way

MIT License

Stars
230
Committers
3

PySwiftyRegex

Pythonのようなスッキリした正規表現ライブラリー。

English 简体中文 한국어

コードをみましょう

import PySwiftyRegex

if let m = re.search("[Tt]his is (.*?)easy", "I think this is really easy!!!") {
	m.group()  // "this is really easy"
	m.group(1) // "really "
}

よく使われるメッソドの用例はこちら

環境

  • iOS 7.0+ / Mac OS X 10.9+
  • Xcode 8.0+

Swift 2.3はバージョン0.3.0をご利用ください。

インストール

Embedded frameworks を使うには iOS 8 または OS X Mavericks 以上は必要です

Deployment Target は iOS 7 のプロジェクトで PySwiftyRegex を使うには, PySwiftyRegex.swift のソースファイルをダウンロードして、Xcodeプロジェクトに追加するのは必要となります。

CocoaPods(iOS 8+, OS X 10.9+)

Cocoapods で簡単に PySwiftyRegex をインストールできます。 下記のようにPodfileを編集してください:

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
	pod 'PySwiftyRegex', '~> 1.0.0'
end

そして、下記のコマンドを実行してください:

$ pod install

Carthage(iOS 8+, OS X 10.9+)

下記の行を CartfileCartfile.private かに追加してください:

github "cezheng/PySwiftyRegex" ~> 1.0.0

そして、下記のコマンドを実行してください:

$ carthage update

最後に、ビルドターゲットのGeneral -> Embedded Binariesに、CarthageがビルドしたPySwiftyRegex.frameworkを追加してください。

対応したreメソッド

re モデルを使ったことがあれば, すぐこのライブラリーをご利用できると思います。もしなかったら、下記のPythonドキュメントのリンクをご覧いただけると、このシンプルなモデルに一目惚れするかもしれませんw

re

re.RegexObject

re.MatchObject

よく使われるメッソドの用例

RegexObjectをコンパイルする

let regex = re.compile("this(.+)that")

文字列の始めからマッチングする

if let m = regex.match("this one is different from that") {
	m.group()  //"this one is different from that"
	m.group(1) //" one is different from "
}

文字列の中にパターンを探す (first match)

if let m = regex.search("I want this one, not that one") {
	m.group()  //"this one, not that one"
	m.group(1) //" one, not "
}

マッチングできた全ての文字列を取得する

regex.findall("this or that, this and that") // ["this or that", "this and that"]

マッチングできた全てのMatchObjectを取得する

for m in regex.finditer("this or that, this and that") {
	m.group()  // 1st time: "this or that", second time: "this and that"
	m.group(1) // 1st time: " or ", second time: " and "
}

パターンで文字列を分割する

let regex = re.compile("[\\+\\-\\*/]")

// デフォルト、全て分割する
regex.split("1+2-3*4/5")    // ["1", "2", "3", "4", "5"]

// 最大分割回数 = 2
regex.split("1+2-3*4/5", 2) // ["1", "2", "3*4/5"]

パターンで文字列を置換する

let regex = re.compile("[Yy]ou")

// 全て置換する (この例は2回)
regex.sub("u", "You guys go grap your food")     // "u guys go grap ur food"
regex.subn("u", "You guys go grap your food")    // ("u guys go grap ur food", 2)

// 最大置換回数を1回にする (この例は1回)
regex.sub("u", "You guys go grap your food", 1)  // "u guys go grap your food"
regex.subn("u", "You guys go grap your food", 1) // ("u guys go grap your food", 1)

ライセンス

PySwiftyRegex のオープンソースライセンスは MIT です。 詳しくはこちら LICENSE