Regular Expressions Razor Pages ASP.NET core @"^[A-Z]+[a-zA-Z""'\s-]*$"?

55 Views Asked by At

What does the '\s-]*$" at the end of @"^[A-Z]+[a-zA-Z""'\s-]*$" stand for? Am I right saying it means no white space and numbers allowed? I understand the start of it, just the last bit is confusing me. And it is the same for @"^[A-Z]+[a-zA-Z0-9""'\s-]*$" Thanks in advance

2

There are 2 best solutions below

4
Chris Barr On BEST ANSWER

Anything inside of square brackets is matching a character or set of characters. So here. I recommend using a tool like Regexr to help you narrow down how it works with whatever input you can provide it.

But I'll break down what this means.

^[A-Z]+[a-zA-Z""'\s-]*$

First of all, ^ means "the beginning of the input string" and $ means "the end of the input string" - So everything in between those characters is what is being matched

There are two character sets being matched

First is [A-Z]+ which means "match any capital letter from A to Z" and then the + at the end means to match the previous set at least one time, but as many times as possible

Next is [a-zA-Z""'\s-]* which is another set that matches:

  • a-z - any lowercase letters from a to z
  • A-Z - any uppercase letter from A to Z
  • "" - any double quote mark. It appears twice here because it must be escaped by the same character in C#
  • ' - any single quote mark
  • \s - any whitespace character like a space or a tab
  • - - a hyphen/dash character

Finally the * at the end means "match the previous set zero or more times, as many times as possible

0
Amit Mohanty On

@"^[A-Z]+[a-zA-Z""'\s-]*$"

  • ^ - This symbol indicates the start of the string.
  • [A-Z]+ - This part matches one or more uppercase letters.
  • [a-zA-Z0-9""'\s-]* - This part is used to match a sequence of characters that can include lowercase letters, uppercase letters, digits (0-9), double quotes (""), single quotes ('), whitespace characters ('\s' which includes spaces, tabs, etc.), and hyphens (-). The asterisk (*) means zero or more occurrences of any of these characters.
  • $ - This symbol indicates the end of the string.