1

I am trying to use Regex to validate a users input on a project I'm working on. The pattern I'm currently using is

^[1-9][0-3]?|[Q|q]$ //Range of 1-13 or Q|q (Can't include 0)

And according to Regex101.com it shows that a users input, say 15, is not a match, yet when I run the project it acts as if it is a match. How do I go about limiting this regex to only accept a range of numbers from 1-13 and the character Q or q? For context just in the event my while loop is wrong here is that code as well.

 while (!match.Success)
        {
            // Ommited Console.WriteLines to for clarity.
            FancyArtBottom();
            Console.SetCursorPosition(47, 19);
            userSelection = Console.ReadLine();
            match = Regex.Match(userSelection, @"^[1-9][0-3]?|[Q|q]$");
        }
  • 5
    Use `^(?:[1-9]|1[0-3]|[Qq])$` – Wiktor Stribiżew Sep 17 '18 at 14:59
  • @WiktorStribiżew what exactly does the : do in regex? Can't seem to locate what it does. I've seen a few people using it before. –  Sep 17 '18 at 15:00
  • It's a non-capturing group. – Fildor Sep 17 '18 at 15:01
  • 1
    See [What is a non-capturing group? What does (?:) do?](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-what-does-do), and this [2-min read](https://www.stefanjudis.com/today-i-learned/non-capturing-groups-in-regular-expressions/). – Wiktor Stribiżew Sep 17 '18 at 15:05

2 Answers2

5

The ^[1-9][0-3]?|[Q|q]$ pattern matches a digit from 1 to 9 followed with an optional digit from 0 to 3 at the start of the string (with ^[1-9][0-3]? part), or (|) a Q, | or q at the end of string (with [Q|q]$ part). So, the | "split" the pattern and it matches more than you expect.

Also, [1-9][0-3]? just matches more than numbers from 0 to 13 as you see.

Besides, the | inside a character class matches a literal | char, it loses its spcial meaning of the alternation operator.

You may use

^(?:[1-9]|1[0-3]|[Qq])$

See the regex demo

Details

  • ^ - start of the string
  • (?:[1-9]|1[0-3]|[Qq]) - a grouping construct (a non-capturing group) (making ^ and $ anchors apply to all the alternatives in the group) matching:
    • [1-9] - a digit from 1 to 9
    • | - or
    • 1[0-3] - 1 and then a digit from 0 to 3
    • | - or
    • [Qq] - q or Q
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

You can use following:

^(1[0-3]|[1-9]|Q|q)$

Or:

^(1[0-3]|[1-9Qq])$

See example: https://regex101.com/r/y6htBi/1

Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27