Nico
Nico

Reputation: 6359

Add a string at the end of a string for a particular string inside a String

I have a big string that contains several strings like the following:

http://website.com/image.jpg and I want to add ?w=100 to each of them.

So far I thought about creating a regular expression where every time I would encounter that string, it would replace it by the same string with the ?w=100 added to it.

Here is an extension of String to replace the string:

public func stringByReplacingMatches(matchRegEx: String, withMatch: String) -> String {
    do {
        let regEx = try NSRegularExpression(pattern: matchRegEx, options: NSRegularExpressionOptions())
        return regEx.stringByReplacingMatchesInString(self, options: NSMatchingOptions(), range: NSMakeRange(0, self.characters.count), withTemplate: withMatch)
    } catch {
        fatalError("Error in the regular expression: \"\(matchRegEx)\"")
    }
}

And this is how I use it:

myString.stringByReplacingMatches("https:\\/\\/website\\.com\\/[\\w\\D]*.jpg", withMatch: "https:\\/\\/website\\.com\\/[\\w\\D]*.jpg?w=100"))

Problem, this is what I get after replacing the string:

https://website.com/[wD]*.jpg?w=100

How can I solve my problem?

Upvotes: 0

Views: 477

Answers (3)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

You need to learn about capture groups:

myString.stringByReplacingMatches("(https:\\/\\/website\\.com\\/[\\w\\D]*.jpg)", withMatch: "$1?w=100")

Oh and don't forget to save the return value

let fixedString = myString.stringByReplacingMatches("(https:\\/\\/website\\.com\\/[\\w\\D]*.jpg)", withMatch: "$1?w=100")

myString will not change, but fixedString will have all the updates.


UPDATE

[\\w\\D]* matches any character. You need to craft a more specific regular expression.

For the input "https://website.com/x.jpg" "https://website.com/x.jpg", the regex \w works.

var myString = "\"https://website.com/x.jpg\" \"https://website.com/x.jpg\""
myString = myString.stringByReplacingMatches("(https:\\/\\/website\\.com\\/\\w*.jpg)", withMatch: "$1?w=100")

But this will not work for every possible URL.

Upvotes: 1

wottle
wottle

Reputation: 13619

You should call it as

myString.stringByReplacingMatches("https:\\/\\/website\\.com\\/[\\w\\D]*.jpg", withMatch: "$0?w=100"))

The template can use $0 to show the matching string. You should not repeat the matching regular expression there.

Upvotes: 1

paulvs
paulvs

Reputation: 12053

do {
    let regex = try NSRegularExpression(pattern: "http:\\/\\/[a-z]*.[a-z]*\\/[a-z]*.[a-z]*", options: .CaseInsensitive)
    var newString = regex.stringByReplacingMatchesInString(a, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, a.characters.count), withTemplate: "$0?w=100")
    print(newString)
}

Upvotes: 0

Related Questions