gpt4 book ai didi

swift - 使用匹配的正则表达式代码替换单词

转载 作者:行者123 更新时间:2023-11-28 05:36:43 26 4
gpt4 key购买 nike

我需要使用 Swift 正则表达式替换给定字符串中的单词。

忽略数字(例如:2000 或 2,000)
但如果数字包含字符,则将其替换(例如:H3llo)

let givenString = "I will keep this 3,000 short. It is a quite common task to 20ff to split a string by 500gg. If you’re a native 500 speaker?"

let range = NSRange(location: 0, length: givenString.count)
var pattern = "[a-zA-Z/\\-']{2,}" // I need the correct pattern, this one if failing.
let regex = try! NSRegularExpression(pattern: pattern, options: [])
print(regex.stringByReplacingMatches(in: givenString, options: [], range: range, withTemplate: "hello"))

结果:

I hello hello hello 3,000 hello. It is a hello hello hello to 20ff to hello a hello by 500gg. If you’re a hello 500 hello?

20ff 和 500gg 应该被替换为“你好”

预期结果:

I hello hello hello 3,000 hello. It is a hello hello hello to hello to hello a hello by hello. If you’re a hello 500 hello?

最佳答案

也许你可以试试:

\d?\S\S+[a-zA-Z]

关于swift - 使用匹配的正则表达式代码替换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com