Issue
Im struggling with regular expressions. Here I have an example !
RegExp timeExp = RegExp(r"^[0-9]{1,2}?:[0-9]{0,2}");
String time1 = "12"; // should be valid
String time2 = "12:30"; // should be valid
String time3 = "123:20:"; // should be valid
String time4 = "123::20:"; // should NOT be valid
String time5 = "12::20:"; // should NOT be valid
String time5 = "1:20:"; // should be valid
if(timeExp.hasMatch(time1)){
print('time1 is valid');
}
if(timeExp.hasMatch(time2)){
print('time2 is valid');
}
if(timeExp.hasMatch(time3)){
print('time3 is valid');
}
if(timeExp.hasMatch(time4)){
print('time4 is valid');
}
if(timeExp.hasMatch(time5)){
print('time5 is valid');
}
The regular expression is not working properly. Could somebody help ?
Thanks in advance.
Solution
You can use
^[0-9]{1,3}(?::[0-9]{1,3})*:?$
See the regex demo. Details:
^
- start of string[0-9]{1,3}
- one, two or three digits(?::[0-9]{1,3})*
- zero or more occurrences of a:
and one, two or three digits:?
- an optional:
$
- end of string.
Another possible solution is
^(?:[0-9]{1,3}(?::|$))+$
See this regex demo, where (?:[0-9]{1,3}(?::|$))+
matches one or more occurrences of one to three digits followed with either :
or $
.
If you need to match any amount of digits in the digit part, replace {1,3}
with +
.
Answered By - Wiktor Stribiżew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.