【问题标题】:Replace words using the matching regex code使用匹配的正则表达式代码替换单词
【发布时间】:2020-02-13 21:15:01
【问题描述】:

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

Ignore numbers (ex: 2000 or 2,000) But if a number contains characters, replace it (ex: 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 应该被替换为 ''hello'

预期:

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?

【问题讨论】:

    标签: swift regex string nsregularexpression nscharacterset


    【解决方案1】:

    也许你可以试试:

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

    【讨论】:

    • 你能解释一下这个正则表达式代码每行的作用吗?
    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    相关资源
    最近更新 更多