Home > Software design >  How can I match this pattern (characters a-z, numbers ) between two brackets?
How can I match this pattern (characters a-z, numbers ) between two brackets?

Time:04-29

I have this code , and I would like to match this pattern:

  • All characters a-z , A-Z between two "" .
  • The variables should be between square brackets.

How can I achieve that?

This input should be accepted :

["a1","a2"]

This is my code and what I've tried:

 string text = "["a1","a2"]";
 Regex rg2 = new Regex(@"[^\""a-z|A-Z|0-9\""$] (, [^\""a-z |A-Z |0-9\""$] ) ");
 if (rg2.IsMatch(text)
      Console.WriteLine("True");

CodePudding user response:

Try this regex \[\"[a-zA-Z0-9] \"(?:,\"[a-zA-Z0-9] \")*]$

https://regex101.com/r/GUbn3K/1

CodePudding user response:

You can use

Regex rg2 = new Regex(@"^\[""[a-zA-Z0-9] ""(?:,\s*""[a-zA-Z0-9] "")*]$");
Regex rg2 = new Regex(@"\A\[""[a-zA-Z0-9] ""(?:,\s*""[a-zA-Z0-9] "")*]\z");

See the C# demo:

string text = "[\"a1\",\"a2\"]";
Regex rg2 = new Regex(@"\A\[""[a-zA-Z0-9] ""(?:,\s*""[a-zA-Z0-9] "")*]\z");
Console.WriteLine(rg2.IsMatch(text)); // => True

Details:

  • \A - start of string
  • \[" - a [" fixed string
  • [a-zA-Z0-9] - one or more ASCII letters/digits
  • " - a double quotation mark
  • (?:,\s*"[a-zA-Z0-9] ")* - zero or more repetitions of
    • , - a comma
    • \s* - zero or more whitespaces
    • "[a-zA-Z0-9] " - ", one or more ASCII alphanumeric chars, "
  • ] - a ] char
  • \z - the very end of string.
  • Related