Vkharb
Vkharb

Reputation: 886

Find a pattern within a string and relace it with another string in swift

There are no straight forward methods in swift to implement and execute regex.

I want to search for numbers within a string and replace it with another string. For ex:

var numberString = "I have 567 horses in my barn"
var replacementString = "many"

How do i search for the indices of existing number and relace them with my string so that it looks like:

var finalString = "i have many horses in my barn"

EDIT : The code should take in consideration of additional formatting on numbers. so that even strings like var numberString = "I have 5,675.00 horses in my barn" can be edited

Upvotes: 0

Views: 89

Answers (3)

rajtharan-g
rajtharan-g

Reputation: 452

var str = "I have 567 horses in my barn"

let decimalCharacters = CharacterSet.decimalDigits

let decimalRange = str.rangeOfCharacter(from: decimalCharacters)

if decimalRange != nil {
    print("Numbers found.. Replace this with the replacement string")
}

From the above usage, you can get the range of the number in the string. Then you can replace that string with your replacement string.

Upvotes: 1

Tj3n
Tj3n

Reputation: 9943

You can use regex:

var numberString = "I have 567 horses in my barn"
var replacementString = "many"
if let range = numberString.range(of: "([0-9])+", options: .regularExpression, range: nil, locale: nil) {
    numberString.replaceSubrange(range, with: replacementString)
}
//Result: "I have many horses in my barn"

Upvotes: 1

vadian
vadian

Reputation: 285240

There are no straight forward methods in swift to implement and execute regex.

let numberString = "I have 567 horses in my barn"
let replacementString = "many"
let finalString = numberString.replacingOccurrences(of: "\\d+", with: replacementString, options: .regularExpression)

Upvotes: 4

Related Questions