Search code examples
regexgoogle-forms

Repeatable regex pattern in Google Forms field validation


I'm new to regular expression and I've got an issue in google forms field validation after a few times trying to find the answer. Here's my current condition (expression in regex101):

[A-Z].*\s[0-9,].+\|$

The expected answer should be: Peter 50|Alex 20|

But when the respondent fills in the field something like Peter 50|Alex| (without the number), it's also a match. How can I force respondents to specify the names and their corresponding numbers in a manner that following a pattern?

Specifically, it should be: Name1 number1|Name2 number2|Name3 number3|Name4 number4|...

Thank you!


Solution

  • The issue is that the .+ matches too much, as the . matches any character.

    You can repeat the matches with a pipe at the end, and start with an uppercase char [A-Z].

    ^(?:[A-Z]\w*\s[0-9]+\|)+$
    
    • ^ Start of string
    • (?: Non capture group
      • [A-Z]\w* Match an uppercase char A-Z and optional word characters
      • \s[0-9]+\| Match a whitspace char and 1+ digits and |
    • )+ Close the group and repeat 1+ times to match multiple occurrences
    • $ End of string

    Regex demo

    If you have names that can contain any non whitespace char, and you meant to match digits with an optional decimal part according to the comma:

    ^(?:[A-Z][^\s|]*\s[0-9]+(?:,\d+)?\|)+$
    
    • ^ Start of string
    • (?: Non capture group
      • [A-Z][^\s|]* Match an uppercase char A-Z followed by 0+ times any non whitespace char except |
      • \s[0-9]+(?:,\d+)?\| Match a whitespace char, 1+ digits and an optional decimal part followed by |
    • )+ Close group and repeat 1+ times
    • $ End of string

    Regex demo