Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

ios - Swift regex for searching format specifiers in a string

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!


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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...