0

I have a requirement that need to write a regular expression to accept only ### ## format. Three numbers, a single space and two more numbers.

I've tried: \d{3}\s?\d{2}$

Can someone help

JvdV
  • 41,931
  • 5
  • 24
  • 46
Yasy
  • 39
  • 3
  • This is a pretty easy regex, you should try it before asking for help. If you are unable to do it, post what you got and we will help you from there. – Nicolas Jan 29 '20 at 14:14
  • What have you tried? What didn't work? What did you get? What did you expect? – Toto Jan 29 '20 at 14:15
  • i tried this new Regex(@"\d{3}\s?\d{2}$"); – Yasy Jan 29 '20 at 14:18
  • And does it work? Because it looks right to me. Can you post a [mcve]? – Lasse V. Karlsen Jan 29 '20 at 14:22
  • Well if it will be strictly that, you can use this. keep it simple and stupid. regexr.com/4t6er – Armin Jan 29 '20 at 14:25
  • 1
    Honestly, this is an incredibly easy regex. Your regex should match what you're trying to match, absent of any other specifications. That said, I'd wager you want to get rid of the `?` after the `\s` if the format is always `### ##` and not `#####` – Zaelin Goodman Jan 29 '20 at 14:26
  • You missed `^` at the start and if the space is not optional remove `?` after `\s` – Wiktor Stribiżew Jan 29 '20 at 15:03

1 Answers1

1

Many ways to do it I guess. This is one of them:

^[\d]{3}[\s]{1}[\d]{2}$
Sebastián Greco
  • 499
  • 6
  • 16
  • 1
    There are many ways to do what he wants to do, including what he already had, which is why we need to find out what the problem is with that. – Lasse V. Karlsen Jan 29 '20 at 14:56
  • Why do you put a simple `\d` or `\s` in a character class? `{1}` is useless. – Toto Jan 29 '20 at 16:04
  • No particular reason. I just tried to do it in a way that it was explicit, not ambiguous and easy to read as each group is defined in a consistent way (char class in group + quantifier with initial and end of line anchors). How your approach would be? – Sebastián Greco Jan 29 '20 at 18:29