问题
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