Reputation: 670
I am using Flutter and dart and I want RegExp to validate strings in the 024648-4568
like format, where a user can only put six numbers at the start, then a -
and then 4 digits at the end.
I started with RegExp(r'^\d{1,6}[\-]?\d{4}')
, but could not fix it for the subsequent dash and 4 digits.
In Flutter, I use it like this:
inputFormatters: [new FilteringTextInputFormatter.allow( RegExp(r'^\d{1,6}-\d{4}') ,]
Upvotes: 1
Views: 2636
Reputation: 626903
You need to make sure the regular expression you use in the FilteringTextInputFormatter
can match a zero- or one-char length string. For example, you can use
RegExp(r'^\d{1,6}(?:-\d{0,4})?$')
See the regex demo. The {1,6}
limiting quantifier makes the first digit required in the input.
More details:
^
- start of string\d{1,6}
- one to six digits(?:-\d{0,4})?
- an optional sequence of
-
- a hyphen\d{0,4}
- zero to four digits$
- end of string.Upvotes: 3