我对正则表达式很陌生,需要用正则表达式来执行特定的任务。我需要一个正则表达式来执行全局搜索,并检查字符串中是否有3个或更多的连续数字,如果是,则将所有数字替换为"xxxx“。
例如,字符串
abcdef 12 quews 4567
应改为
abcdef XX quews XXXX
任何帮助都将不胜感激。谢谢。
发布于 2018-03-21 11:16:56
谢谢你所有的答案,通过你的输入,我能够用下面的代码来解决这个问题
extension String {
func replaceDigits() -> String {
do {
let regex = try NSRegularExpression(pattern: "\\d{3,}", options: [])
let matches = regex.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: self.count))
if matches > 0 {
return replacingOccurrences(of: "\\d", with: "X", options: .regularExpression, range: nil)
}
} catch {
return self
}
return self
}
}发布于 2018-03-07 09:11:23
已更新
使用此
func testingRegex6(text:String) ->String{
do{
var finalText = text
let componentNSString = NSString.init(string:text)
let regex = try NSRegularExpression(pattern: "\\d+", options:[.dotMatchesLineSeparators])
let matches = regex.matches(in: text ,options: [], range: NSMakeRange(0, componentNSString.length)).reversed()
if(matches.filter({$0.range.length >= 3}).count > 0) { //here we check if we have any substring containing 3 o more digits
for result3 in matches {
finalText = finalText.replacingOccurrences(of: componentNSString.substring(with: result3.range), with: Array(repeating: "X", count: result3.range.length).joined())
}
}
return finalText
}
catch{
return ""
}
return ""
}输入 "abcdef 12 quews 4567“Log "abcdef XX quews XXXX” 输入 "abcdef 12 que82ws 45“Log "abcdef 12 que82ws 45”
发布于 2018-03-07 09:12:51
用这个,
let testString = "abcdef 12 quews 4567"
let output = testString.replacingOccurrences(of: "[\\[\\]^[0-9]]", with: "X", options: .regularExpression, range: nil)
print(output)你的输出是这样的,
abcdef XX quews XXXX更新
查找字符串扩展类,
extension String {
func matches(for regex: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))
return results.map {
String(self[Range($0.range, in: self)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}找到下面的代码,
let temp = "abc44def 12 quews 4564 1254"
let array = temp.matches(for: "\\d{3,}")
var output = temp
for val in array.enumerated() {
var string = ""
for _ in 0..<val.element.count {
string+="X"
}
output = output.replacingOccurrences(of: val.element, with: string)
}
print(output)你会得到这样的输出,
abc44def 12 quews XXXX XXXXhttps://stackoverflow.com/questions/49147442
复制相似问题