16
19

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で正規表現を使って文字列を置換する

Posted at

String.replacingOccurrencesのオプションに.regularExpressionを指定します。また、後方参照は\1{1}でなく$1です。以下、twitterのプロフィール画像URLを置換する例です。

extension String {
    func twttrPhoto() -> String {
        return replacingOccurrences(
            of: "^https?://(.+)_normal(.+)$",
            with: "https://$1$2",
            options: .regularExpression,
            range: self.range(of: self))
    }
}
let url = "http://pbs.twimg.com/profile_images/1610656772/nTotani_normal.jpg"

url.twttrPhoto()
// => https://pbs.twimg.com/profile_images/1610656772/nTotani.jpg

先頭がhttpsになり、_normalが取り除かれています。

16
19
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
16
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?