正则表达式查找和替换数字

时间:2018-03-07 08:41:24

标签: ios regex swift4

我是正则表达式的新手,需要执行相同的特定任务。我需要一个执行全局搜索的正则表达式,并检查字符串中是否有3个或更多连续数字,如果是,则用“xxxx”替换所有数字。

例如,字符串

  

abcdef 12 quews 4567

应改为

  

abcdef XX遇到XXXX

任何帮助将不胜感激。感谢。

5 个答案:

答案 0 :(得分:1)

已更新

使用此

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" 记录" abcdef XX烦恼XXXX"

     

输入" abcdef 12 que82ws 45" 记录" abcdef 12 que82ws 45"

答案 1 :(得分:0)

使用此,

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 XXXX

答案 2 :(得分:0)

用Reg。表达

let txt = "abc 12 wqer 987asd asdf1233sadf"
do {
    let regx = try NSRegularExpression(pattern: "[0-9]", options: .caseInsensitive)

    let result = regx.stringByReplacingMatches(in: txt, options: .withTransparentBounds, range: NSMakeRange(0, txt.count), withTemplate: "X")

    print(result)

} catch {
    print(error)
}

没有注册。表达

let txt = "abc 12 wqer 987asd asdf1233sadf"

let replacedStr = String(txt.map {

  let c = String($0)
  if let digit = Int(c), digit >= 0, digit <= 9 {
      return "X"
  } else {
      return $0
  }
})
print(replacedStr)

答案 3 :(得分:0)

let characters = Array(str)

将字符串转换为字符串数组

var count = 0
for i in characters {

     if i >= "0" && i <= "9" {
         count += 1
      }
}
if count > 3 {

 let output = str.replacingOccurrences(of: "[\\[\\]^[0-9]]", with: "X", options: .regularExpression, range: nil)
        print(output)
}

使用带计数器的循环,如果数字大于3,则替换字符串。

Result

答案 4 :(得分:0)

感谢您的所有答案,通过以下代码,我能够解决所有问题

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
    }
}