简体   繁体   English

为什么这个 swift 中的正则表达式不起作用?

[英]Why this regular expression in swift doesn't work?

Edited:编辑:

I am trying to replace words in string using regex in Swift 5.我正在尝试在 Swift 5 中使用正则表达式替换字符串中的单词。

my code:我的代码:

    let text = "hi avoid avoid avoid"
    let regex = "/(avoid|another word|word3)/gi"
    let str = text.replacingOccurrences(of: regex, with: "", options: [.regularExpression])

    print(str) // will print: "hi avoid avoid avoid"

expected result:预期结果:

print(str) // will print: "hi "

So the regex should remove any avoid, another word or word3 words from the string所以正则表达式应该从字符串中删除任何避免、另一个词或 word3 词

any help?有什么帮助吗?

let myString = "hi avoid avoid avoid"
let regex = try! NSRegularExpression(pattern: "(avoid|another word|word3)", 
                   options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, myString.count)
let modString = regex.stringByReplacingMatches(in: myString, options: [], 
                  range: range, withTemplate: "")
print(modString)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM