I had to play around with it quite a bit to get it to work as I am not that familiar with regular expressions, but here's what I believe will work best.
Use the System.Text.RegularExpressions library.
Within it is a class called
RegEx
.
Create a new
RegEx
class like:
Regex myRegEx = new RegEx("^\d+((,\d+)*)$")
(that was my clumsy conversion from VB)...that won't work in C#. In C#, it should be:
RegEx myRegEx = new RegEx(@"^\d+((,\d+)*)$");
Then, pass the string you want to match in using
myRegEx.IsMatch(stringToTest)
.
If it is true, then it should only have
letters numbers and commas. If false, it has something else.
I tested the following and got the following results:
"483,3929,2020" True
"3939,2902s,1292" False
"A394" False
"394,394" True
"394,394s" False
"394" True
So, I'll try to explain what it's doing in case you aren't familiar with regular expressions.
The caret (^) tells it to start at the beginning. "\d+" tells it to look for one or more digits. So the first block "^d\+" says "start at the beginning and check for as many digits as there are. Then it moves on to the next block ("((,\d+)*)$").
The (...)$ says whatever is inside of it has to be at end of the string for this to match. And it will start whenever the previous test fails (so when there isn't a digit).
The (,\d+) says when there isn't a digit check to see if it's a comma. If it isn't, it will fail. If it is, it will then check for digits again (as many as there are). The (...)* says find as many of those as possible. So, it will look first for digits. Then, a comma and more digits and it will repeat looking for a comma and more digits until it gets to the end. If it doesn't end with that pattern, it will fail.