Rajesh Rs
Rajesh Rs

Reputation: 1391

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

Upvotes: 2

Views: 653

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627600

You may use

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

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

Details

  • (\G(?!^)|(?<!\d\.)\b[0-9]+\.[0-9]) - Group 1: the end of the preceding successful match (\G(?!^)) or (|) 1+ digits, . and a digit that are not immediately preceded with a digit and a dot, and that can not have a non-word char right before them ((?<!\d\.)\b[0-9]+\.[0-9])
  • ([0-9]) - Group 2: a digit.

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

Upvotes: 1

Related Questions