3
3

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.

Swiftはじめたい...その17 正規表現が面倒すぎるので...

Last updated at Posted at 2016-02-15
  • Swiftってネイティブに正規表現使えないんですね。今時そんなんじゃやってられませんよ!

やっぱりperlですよね!

  • ...ってawkとかでもいいんですが...

NSTaskを使えば...

  • Mac専用ですがperlを呼び出しちゃえ!
  • playgroundじゃなくてswiftcでコンパイルしてください。
perlを呼び出す。
import Foundation

func regexp(str:String)->String {
    let task = NSTask()
    task.launchPath = "/opt/local/bin/perl"
    task.arguments = ["-e","{my $s='\(str)';if ( my @d = ($s =~ m/(\\d*)/g) ) { print join(',',@d) } }"]
    let pipe = NSPipe()
    task.standardOutput = pipe
    task.launch()

    let output = pipe.fileHandleForReading.readDataToEndOfFile()
    
    return String(NSString(data:output,encoding:NSUTF8StringEncoding)!)
}

let result = regexp("0A1B123C190")
print(result)
結果
0,,1,,123,,190,
  • なんてね、(๑´ڡ`๑)

まとめ

  • swift2.2とかswift3.xでは正規表現を簡単に使わせて!
3
3
4

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?