1

I'm trying to create regexp with format "dd-dd-dd" in Swift

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.

2
  • Only one dash between number is correct. Commented Apr 16, 2019 at 17:52
  • Why is -12-32 correct? It starts with -. I'd suggest let pattern = "^\\d{1,2}(?:-(?:\\d{1,2}(?:-\\d{0,2})?)?)?$", see regex101.com/r/eHHG2l/1. Commented Apr 16, 2019 at 18:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe not perfect, but it works and that's exactly what l wanted. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.