Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need help to write the swift regex to find any format specifier in a string.

Eg.

"I am %@. My age is %d and my height is %.02f."

I need to find all sub-strings in bold and replace them with 'MATCH'

Below is my code

var description = "I am %@. My age is %d and my height is %.02f. (%@)"
let pattern = "(%[@df])"
let regex = try NSRegularExpression(pattern: pattern, options: [])
let nsrange = NSRange(description.startIndex..<description.endIndex, in: description)

while let match = regex.firstMatch(in: description, options: [], range: nsrange) {
    description = (description as NSString).replacingCharacters(in: match.range, with: "MATCH")
}
print(description)

and output

I am MATCH. My age is MATCH and my height is %.02f. (%@)

It did not find %.02f and last %@ with paranthesis.

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
436 views
Welcome To Ask or Share your Answers For Others

1 Answer

First of all you have to replace the matches reversed otherwise you will run into index trouble.

A possible pattern is

%([.0-9]+)?[@df]

it considers also the (optional) decimal places specifier.

var description = "I am %@. My age is %d and my height is %.02f. (%@)"
let pattern = "%([.0-9]+)?[@df]"
let regex = try NSRegularExpression(pattern: pattern)
let nsrange = NSRange(description.startIndex..., in: description)

for match in regex.matches(in: description, range: nsrange).reversed() {
    let range = Range(match.range, in: description)!
    description.replaceSubrange(range, with: "MATCH")
}
print(description)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...