3

I am trying to remove any URL within a string, and there is a SO answer that provides a solution using regular expression in PHP:

$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
echo preg_replace($regex, ' ', $string);

I tried directly in Swift as:

myStr.stringByReplacingOccurrencesOfString("@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@", withString: "", options: .RegularExpressionSearch)

but it shows some error Invalid escape sequence in literal.

How to do it correctly in Swift?

Community
  • 1
  • 1
Joe Huang
  • 6,296
  • 7
  • 48
  • 81
  • Remove the enclosing `@` and double backslashes. I think you do not need to pass any options either, use `options: []` – Wiktor Stribiżew Apr 03 '16 at 09:17
  • You can not use / key in strings. Because / breaks string syntax. We use / for intercept string quotes and convert some values to string. Ex: "age: \ (18)" So you can not start with / character. – emresancaktar Apr 03 '16 at 09:45

2 Answers2

8

If you want remove urls from string without using regular expressions you can use this code:

import Foundation

extension String {
    func removingUrls() -> String {
        guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
            return self
        }
        return detector.stringByReplacingMatches(in: self,
                                                 options: [],
                                                 range: NSRange(location: 0, length: self.utf16.count),
                                                 withTemplate: "")
    }
}
5

First, you need to escape the escape character "\", so every "\" becomes "\\". Second, you miss the 4th parameter, i.e. "range:"

import Foundation

let myStr = "abc :@http://apple.com/@ xxx"
myStr.stringByReplacingOccurrencesOfString(
    "@(https?://([-\\w\\.]+[-\\w])+(:\\d+)?(/([\\w/_\\.#-]*(\\?\\S+)?[^\\.\\s])?)?)@", 
    withString: "", 
    options: .RegularExpressionSearch, 
    range: myStr.startIndex ..< myStr.endIndex
)

// result = "abc : xxx"
roel
  • 1,640
  • 14
  • 13
  • I found I can use these regular expressions directly from Java's answers: http://stackoverflow.com/questions/11007008/whats-the-best-way-to-check-if-a-string-contains-a-url-in-java-android – Joe Huang May 02 '16 at 01:06