i have regex match date format comma.
yyyy/mm/dd or yyyy/mm
for example:
2016/09/02,2016/08,2016/09/30
my code:
string data="21535300/11/11\n"; regex reg = new regex(@"^(20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|30|31))?,?)*$", regexoptions.multiline); if (!reg.ismatch(data)) "error".dump(); else "true".dump();
i use option multiline. if string data have "\n". character match regex.
for example:
string data="test\n" string data="2100/1/1"
i find option definition in msdn. says:
it changes interpretation of ^ , $ language elements match beginning , end of line, instead of beginning , end of input string.
i didn't understand why problem has happened. can explan it? thanks.
your regex can match empty line once add newline @ end of string. "test\n"
contains 2 lines, , second 1 gets matched.
see regex pattern in free-spacing mode:
^ # matches start of line ( # start of group 1 20\d{2}/ (0[1-9]|1[012]) (/ (0[1-9]|[12]\d|30|31) )?,? )* # end of group 1 - * quantifier makes match 0+ times $ # end of line
if not want match empty line, replace last )*
)+
.
an alternative use more unrolled pattern like
^20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|3[01]))?(,20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|3[01]))?)*$
see regex demo. inside code, advisable use block , build pattern dynamically:
string date = @"20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|3[01]))?"; regex reg = new regex(string.format("^{0}(,{0})*$", date), regexoptions.multiline);
as can see, first block (after start of line ^
anchor) obligatory here, , empty line never matched.
Comments
Post a Comment