C# Regex - if string only contains a character
Us开发者_Python百科ing C#/Regex, how do I find a string that only contains commas and no alphanumeric (or other non-comma) symbols?
a: ',,,,,,,' match
b: ',,,,,,#A' no match
[^,]
If that matches, that means a string contains a non-comma character.
A more complete example:
if (!Regex.IsMatch(yourTestString, "[^,]"))
{
// This string does NOT contain commas
}
This should do it:
var text = ",,,";
Regex.IsMatch(text, @"^,+$"); // true
If I read your question correctly, you want to know if a string contains only commas.
If so, use this regex: ^[,]+$
.
This will only match on strings that contain one or more commas and nothing else.
A string of only commas?
Regex.IsMatch(str, @"^,*$");
That will tell you whether or not str
consists entirely of commans or not.
I'd suggest that, as a one-char regex will always have to examine each character of its input string in the worst case, a simple for-loop will definitely be more efficient. Something like this will give the exact same effect in less time and space than any equivalent Regex
:
private void IsOnlyOneChar(string input, char c)
{
for (var i = 0; i < input.Length; ++i)
if (input[i] != c)
return false;
return true;
}
Not literally the answer you were looking for, but in my opinion this is your optimal solution.
精彩评论