简体   繁体   English

如何检查UITextField中的文本是否匹配特定模式?

[英]How to check if text in a UITextField matches a specific pattern?

I have a UITextField and I need to check, as the user types, if the text they have entered in the textfield so far matches a specific pattern. 我有一个UITextField,并且在用户输入时需要检查他们到目前为止在文本字段中输入的文本是否与特定模式匹配。

More specifically, I need the text to match the pattern ####-##-## where # is any digit 0-9 and - is a dash (note that this is NOT a phone number or email). 更具体地说,我需要文本匹配模式####-##-## ,其中#是0-9的任何数字,而-是破折号(请注意,这不是电话号码或电子邮件)。 For example, the entry 1990-12-09 matches, 1990:12:09 does not match and 1990-12 DOES match because it has not yet violated the pattern (even though the text does not yet completely match the pattern). 例如,条目1990-12-09匹配, 1990:12:09不匹配,而1990-12匹配,因为它尚未违反模式(即使文本尚未完全匹配该模式)。

How should I approach this? 我应该如何处理? Ideally I would not have to hard code in a series of if statements . 理想情况下,我不必在一系列if语句中进行硬编码。

The difficulty is that I want to check if the text in the textfield matches this pattern, as the user types . 困难在于, 随着用户键入 ,我想检查文本字段中的文本是否与此模式匹配。 I don't want to just check it at the end. 我不想只在最后检查一下。

I'm thinking that regular expressions are probably the way, but I'm not experienced enough at them to know if they hold the solution. 我认为正则表达式可能是这种方式,但是我对它们的经验不足,无法知道它们是否具有解决方案。

You could set the keyboard type to myTextField.keyboardType = UIKeyboardTypeNumberPad that why you are limiting the type of input. 您可以将键盘类型设置为myTextField.keyboardType = UIKeyboardTypeNumberPad ,这就是您限制输入类型的原因。

Then this post should help answer your formatting question: UITextField format in xx-xx-xxx 然后,该帖子应有助于回答您的格式问题: xx-xx-xxx中的UITextField格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM