LoginSignup
31
26

More than 5 years have passed since last update.

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

Posted at

PySwiftyRegex

私が前に作った正規表現のライブラリは今週のSwiftSandbox Issueに当選しましたw

Pythonのreのようなスッキリした正規表現ライブラリーです。よろしければ、どうぞお使いくださ(CocoaPods, Carthage対応あり)

日本語のREADMEもあります https://github.com/cezheng/PySwiftyRegex/blob/master/README-ja.md

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

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)

もっと詳しい情報はgithubのREADMEをご覧ください。

31
26
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
31
26