tags:

views:

173

answers:

2

Hi guys,

I've tried several regex combinations to figure out this, but some or the condition fails,

I have an input string, that could only contain a given set of defined characters

lets say A , B or C in it.

how do I match for something like this?

ABBBCCC -- isMatch True

AAASDFDCCC -- isMatch false

ps. I'm using C#

+18  A: 
 ^[ABC]+$

Should be enough: that is using a Character class or Character Set.

The Anchors '^' and '$' would be there only to ensure the all String contains only those characters from start to end.

Regex.Match("ABACBA", "^[ABC]+$"); // => matches

Meaning: a Character Set will not guarantee the order of he characters matched.

Regex.Match("ABACBA", "^A+B+C+$"); // => false

Would guarantee the order

VonC
Thanks VonC, Works Perfect, I was using [ABC]+ which I thought would be fine, but the Anchor and $ are required.... Cheers!!
81967
Thanks for the ordering tip, that is going to help me out.
JasonBartholme
+1  A: 

I think you are looking for this:


Match m = Regex.Match("abracadabra", "^[ABC]*$");
if (m.Success) {
   // Macth
}
NawaMan
"^[ABC]*$" will also match an empty string. To force at least one of the chars to be present, change it to "^[ABC]+$"
Andre Miller