c# - Compare and validate two strings -
// = alphabetic, x = alphanumeric, n = numeric character string strformatching = "aaaaxxxx-nnnn-aa"; string[] strtobevalidated = new string[] { "333test", "test4444-1234-ab", "abcd12ab-1234-99", "abcd2345-1234-ab", "ppp12aa-9876" }; with for loop passing each string string array method
public bool validatestring(string strformatching, string strtobevalidated) { bool isvalid = false; // put here? return isvalid; } i want validate strtobevalidated strformatching.
that means:
333testnot validabcd2345-1234-abvalidppp12aa-9876validppppp12ax-1234-abnot valid.
what ever value there should match strformatching. need validate separator.
i can not use regular expression because have aaaaxxx-nnnn-aa, in case 1 4 alphabet okay valid more 4 alphabet not valid same x , n , separate can change / or # or @ anything. if i'll use regular expression check till fix length
this regular expression seems work expected
string[] strtobevalidate = new string[] {"333test", "test4444-1234-ab", "abcd12ab-1234-99", "abcd2345-1234-ab", "ppp12aa-9876" }; regex r = new regex(@"[a-za-z]{4}[a-za-z0-9]{4}-[0-9]{4}-[a-za-z]{2}"); foreach(string s in strtobevalidate) { match m = r.match(s); if(m.success == false) console.writeline("no match for: " + s); else console.writeline(m.tostring()); } meaning:
- first set of 4 characters
{4}should in range a-z (upper case) or a-z (lower case) - the second set of 4 character should before contains numbers 0-9
- a minus symbol follow
- the third set of 4 characters numbers
- a minus symbol follow
- the fourth set of 2 characters alphabetich characters
now applying regex pattern input strings find match second , fourth string.
looking @ comment have tried build simple pattern builder.
string buildpattern(string h) { stringbuilder sb = new stringbuilder(); string curpattern = ""; char curchar = ' '; int cnt = 0; foreach(char c in h) { if(c != curchar && cnt != 0) { sb.append(curpattern); sb.append("{" + cnt.tostring() + "}"); cnt = 0; curpattern = ""; } curchar = c; switch(c) { case 'a': curpattern = "[a-za-z]"; cnt++; break; case 'x': curpattern = "[a-za-z0-9]"; cnt++; break; case 'n': curpattern = "[0-9]"; cnt++; break; default: sb.append(c); break; } } sb.append(curpattern); sb.append("{" + cnt.tostring() + "}"); return sb.tostring(); } and change code prepare regex pattern one:
string strformatching = "aaaannaa-nnnn-nn"; string pattern = buildpattern(strformatching); // fixed -> regex r = new regex(@"[a-za-z]{4}[a-za-z0-9]{4}-[0-9]{4}-[a-za-z]{2}"); // dynamic pattern regex r = new regex(pattern); however need tested more extensively......
Comments
Post a Comment