简体   繁体   English

将字符串与 swift 中的正则表达式部分匹配

[英]Partial matching a string against a regex in swift

I'm trying to create regexp with format "dd-dd-dd" in Swift我正在尝试在 Swift 中创建格式为“dd-dd-dd”的正则表达式

I came up with this :我想出了这个:

(\d{1,2})(-)(\d{1,2})(-)(\d{1,2})

This pattern gives me correct result if the string is given as a whole.如果字符串作为一个整体给出,则此模式给我正确的结果。 Example :例子 :

12-32-42 -> correct
2-32-1   -> correct
2--32-3  -> incorrect

I will be using this pattern in textfields.我将在文本字段中使用这种模式。 What I would like to know is if the typed string is heading towards positive regexp check.我想知道的是,输入的字符串是否正朝着正则表达式检查方向发展。 Example :例子 :

12     -> correct
-12-32 -> correct
12-    -> correct
-12--  -> incorrect

I will be grateful for any help you can provide.如果您能提供任何帮助,我将不胜感激。

One option could be to list to possible combinations in an alternation :一种选择是在交替中列出可能的组合:

^(?:\d{1,2}-\d{1,2}-\d{1,2}|\d{1,2}-|-\d{1,2}-\d{1,2}|\d{1,2})$

Regex demo正则表达式演示

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

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