iosswiftregexreplace

Swift regex for matching a decimal part of the number in a string and modify it


Below is my requirement

given_string = "The total amount for 345 days is 123.4567 Euros"

the decimal part(substring) in the above string has to be inserted with spaces as shown below converted_string = "The total amount for 345 days is 123.4 5 6 7 Euros"

I came up with below code

func reformatDecimalInStr() -> String {
    let pattern = "(?<=[0-9]|\\.)[0-9](?=[0-9]+)"
    return self.replacingOccurrences(of: pattern, with: "$0 ", options: .regularExpression, range: nil)
}

but the output is like The total amount for 34 5 days is 12 3.4 5 6 7 Euros. where, "345" is converted to "34 5" "123.4567" to "12 3.4 5 6 7" which is not desired

here the positive lookbehind will check for "." or a numeric whereas what i require is "." is matched with 0 or more numeric in between.

thanks in advance


Solution

  • You may use

    (\G(?!^)|(?<!\d\.)\b[0-9]+\.[0-9])([0-9])
    

    Replace with $1 $2. See the regex demo.

    Details

    Swift example:

    let given_string = "The total amount for 345 days is 123.4567 Euros"
    let regex = "(\\G(?!^)|(?<![0-9]\\.)\\b[0-9]+\\.[0-9])([0-9])"
    let result = given_string.replacingOccurrences(of: regex, with: "$1 $2", options: .regularExpression)
    print(result)
    // => The total amount for 345 days is 123.4 5 6 7 Euros