JYou
JYou

Reputation: 9

Swift: How to find a replace a a group of characters in a string, starting from a predefined character and ending with another

I am currently working on a project, and am close to finishing. I just have one problem.

I have extra random stuff in the string that I want to get rid of. something like ""

What I want to do is this:

var infoFormat: String = "Hello, I like <ck4icl;alekdinl;dlke>pancakes!"
infoFormat = infoFormat.replacingOccurrences(of: "<" to ">", with: "", options: .literal, range: nil)

print(infoFormat)
// prints "Hello, I like pancakes!"

Is there a way to achieve this? Much thanks to anyone that tries to help.

Upvotes: 0

Views: 93

Answers (3)

vadian
vadian

Reputation: 285072

This regular expression removes all characters between < and >

var infoFormat = "Hello, I like <ck4icl;alekdinl;dlke>pancakes!"
infoFormat = infoFormat.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression)

The pattern searches for < followed by one or more characters which are not > and a closing >

Upvotes: 2

SKD
SKD

Reputation: 1493

Can try like:

var infoFormat = "Hello, I like <ck4icl;alekdinl;dlke>pancakes!"

    var startIndex = infoFormat.startIndex

    while let from = infoFormat.range(of: "<", range: startIndex..<infoFormat.endIndex)?.lowerBound,
        let to = infoFormat.range(of: ">", range: from..<infoFormat.endIndex)?.upperBound,
        from != to {
            infoFormat.removeSubrange(from..<to)
            startIndex = from
    }

    print(infoFormat)
    
    /// OR ///
    
    let parsed = infoFormat.replacingOccurrences(of: "<ck4icl;alekdinl;dlke>", with: "")
    print(parsed)

Note: You can use replacingOccurrences if you know the sub-string to remove, else use first one.

Output:

Hello, I like pancakes!

Hello, I like pancakes!

Thanks

Upvotes: 0

Keshu R.
Keshu R.

Reputation: 5225

Try this:

    let infoFormat: String = "Hello, I like <ck4icl;alekdinl;dlke>pancakes!"
    let stringFirstIndex = infoFormat.firstIndex(of: "<")
    let firstIndex = infoFormat.index(stringFirstIndex!, offsetBy: 0)
    let stringLastIndex = infoFormat.firstIndex(of: ">")
    let lastIndex = infoFormat.index(stringLastIndex!, offsetBy: 0)
    let finalString = infoFormat.replacingCharacters(in: firstIndex...lastIndex, with: "")
    print(finalString)

Make sure to safely unwrap the optional.

Upvotes: 0

Related Questions