'How can I match this pattern (characters a-z, numbers ) between two brackets?
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");
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
