Home > Software design >  Flutter regular expressions
Flutter regular expressions

Time:12-27

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.

CodePudding user response:

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 .

CodePudding user response:

With your shown samples, please try following regex.

^(?:[0-9]{1,3})(?::[0-9]{1,3}[:]?)?$

Online demo for above regex

Explanation: Adding detailed explanation for above regex.

^(?:[0-9]{1,3})  ##Matching from starting of value in a non-capturing group 1 to 3 digits here.
(?:              ##Starting another non-capturing group from here.
  :[0-9]{1,3}    ##Matching colon followed by 1 to 3 occurrences of digits here.
  [:]?           ##Matching 0 or 1 colon occurrences here.
)?$              ##Keeping this non-capturing group as optional at end of value.
  • Related