swift中的正则表达式不适用于此示例? [英] regex in swift is not working with this example?

查看:161
本文介绍了swift中的正则表达式不适用于此示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式,但这不起作用,我不明白为什么。 println 未显示在输出中。我按照教程使用此

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.

当我不使用时,代码返回文本正则表达式。如果我使用它,则不会出现 println 。我试过(/([az] +)|([0-9] +)/ ig)$/([az ] +)|([0-9] +)/ ig $但它们都不起作用。

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


推荐答案

在这种情况下,您不需要使用(/ ..... / ig)$,所以试试这个:

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

这篇关于swift中的正则表达式不适用于此示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆