Swift正则:仅为字符串中小数部分数字添加空格的问题修正
Ah, I see the issue with your regex! The original pattern is matching digits within integers because the positive lookbehind (?<=[0-9]|\.) allows any digit before the target digit — which hits numbers like 345 (matching the 4, since it's after 3) and 123 (matching 2, since it's after 1).
To fix this, we need to restrict the matching only to digits that come after a decimal point, and are part of the fractional part of the number. Here's how to adjust your code:
func reformatDecimalInStr() -> String { // Updated regex to target only fractional digits let pattern = "(?<=\\.\\d*)[0-9](?=[0-9]+)" return self.replacingOccurrences(of: pattern, with: "$0 ", options: .regularExpression, range: nil) }
Let's break down the corrected regex to understand why it works:
(?<=\\.\\d*): This positive lookbehind ensures we're positioned after a decimal point followed by zero or more digits. This locks us into the fractional section of a number, so we never touch integer digits.[0-9]: Matches a single digit in the fractional part.(?=[0-9]+): This positive lookahead ensures the digit we're matching has at least one more digit after it. This skips the final digit in the fractional part, so we don't add an unnecessary trailing space.
When you run this with your input string:
The total amount for 345 days is 123.4567 Euros
It will output exactly the result you want:
The total amount for 345 days is 123.4 5 6 7 Euros
内容的提问来源于stack exchange,提问作者Rajesh Rs

