c# - Using Regex to determine if string contains a repeated sequence of a particular substring with comma separators and nothing else -
i want find if string contains repeated sequence of known substring (with comma separators) , nothing else , return true if case; otherwise false. example: substring "0,8"
string a: "0,8,0,8,0,8,0,8" returns true string b: "0,8,0,8,1,0,8,0" returns false because of '1'
i tried using c# string functions contains not suit requirements. totally new regular expression feel should powerful enough this. regex should use this?
the pattern string containing nothing repeated number of given substring (possibly 0 of them, resulting in empty string) \a(?:substring goes here)*\z
. \a
matches beginning of string, \z
end of string, , (?:...)*
matches 0 or more copies of matching thing between colon , close parenthesis.
but string doesn't match \a(?:0,8)*\z
, because of commas; example match "0,80,80,80,8". need account commas explicitly \a0,8(?:,0,8)*\z
.
you can build such thing in c# thus:
string oksubstring = "0,8"; string aok = "0,8,0,8,0,8,0,8"; string bok = "0,8,0,8,1,0,8,0"; regex okregex = new regex( @"\a" + oksubstring + "(?:," + oksubstring + @")*\z" ); okregex.ismatch(aok); // true okregex.ismatch(bok); // false
that hard-codes comma-delimiter; make more general. or maybe need literal regex. either way, that's pattern need.
edit changed anchors per mike samuel's suggestion.
Comments
Post a Comment