Vishal_Kotecha
Vishal_Kotecha

Reputation: 491

Regex string should contain Double quotes and comma seperated numbers only

I have following string

"56565665,5656565,5656556"

I want to just check that the string must only contain Double quotes, Comma and numbers.

for that I have tried creating a regex ^"\d+\, but it only selects first string.

I am new to regex completely.

Upvotes: 0

Views: 128

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

You can try the pattern below:

 ^"[0-9]+(,[0-9]+)*"$

or even

 \A"[0-9]+(,[0-9]+)*"\z //  Wiktor Stribiżew's idea, see his comment below 

E.g.

 string source = @"""123,456,789""";
 string pattern = @"\A""[0-9]+(,[0-9]+)*""\z";

 bool result = Regex.IsMatch(source, pattern);

Tests:

 "123"       - true  // just a number
 "123,456"   - true  // two numbers separated by comma
 "1,2,3,4"   - true  // four numbers separated by comma 
 ","         - false // just a comma, no numbers
 ",123"      - false // leading comma
 "123,"      - false // trailing comma
 "123,,456"  - false // double comma

Upvotes: 1

DAXaholic
DAXaholic

Reputation: 35358

You can use ^"[\d,]+"$

See it here on regex101

In C# it would look like this due to escaping chars

using System.Text.RegularExpressions
...
Console.WriteLine(Regex.IsMatch(@"""56565665,5656565,5656556""", @"^""[\d,]+""$"));
Console.WriteLine(Regex.IsMatch(@"""56565665,5656565;5656556""", @"^""[\d,]+""$"));

Update due to question in comments about how to use it with a variable:

var str = @"""56565665,5656565,5656556""";
// var str = "\"56565665,5656565,5656556\""; <- Alternative way of escaping "  

Console.WriteLine(Regex.IsMatch(str, @"^""[\d,]+""$"))

Upvotes: 3

NishantMittal
NishantMittal

Reputation: 537

Try this , hope this will work "^[0-9,]+$"

Upvotes: 1

Related Questions