LoginSignup
2
1

More than 3 years have passed since last update.

特定の文章から URL を削除(置換)する

Posted at

やること

I like http://hoge.com and https://piyo.net.

この文章から URL を削除して

I like and .

にしたいと思います。

Playground
import UIKit

var input = "I like http://hoge.com and https://piyo.net."
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))

var urls: [String] = []
for match in matches {
    guard let range = Range(match.range, in: input) else { continue }
    let url = input[range]
    urls.append(String(url))
}
print(urls)
urls.forEach{ url in
    input = input.replacingOccurrences(of: url, with: "")
}
print(input)
output
["http://hoge.com", "https://piyo.net"]
I like  and .

できました。

2
1
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
2
1