regex in swift is not working with this example?

 ̄綄美尐妖づ 提交于 2019-12-02 16:09:12

问题


I am trying to use Regex expressions but this does not work and I don't understand why. The println is not showing up in the output. I followed this tutorial to use this class:

class Regex {
  let internalExpression: NSRegularExpression
  let pattern: String

  init(_ pattern: String) {
    self.pattern = pattern
    var error: NSError?
    self.internalExpression = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)
  }

  func test(input: String) -> Bool {
    let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input)))
    return matches.count > 0
  }
}

And this other tutorial to create the Regex.

The code returns the text when I do not use Regex. If I do use it, the println does not appear. I tried "(/([a-z]+)|([0-9]+)/ig)$" and "/([a-z]+)|([0-9]+)/ig$" but none of them work.

func textFieldDidEndEditing(textField: UITextField) {
        println("end editing")

        if let match = textField.text.rangeOfString("/([a-z]+)|([0-9]+)/ig$", options: .RegularExpressionSearch) {
            println("\(match) is probably f**ked off and left as a f**king bastard")
        }

        if Regex("/([a-z]+)|([0-9]+)/ig").test(textField.text){
            println("yes")
            textField.text = textField.text.uppercaseString
        }
    }

回答1:


In this case, you do not need to use (/ ..... /ig)$, so try this:

   if let match = textField.text.rangeOfString("([a-z]+)|([0-9]+)", options: .RegularExpressionSearch) {
                println("\(match) is bla bla bla...")
            }

It will be work and return the range of the first occurrence of a given string



来源:https://stackoverflow.com/questions/28797758/regex-in-swift-is-not-working-with-this-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!