1

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}') ,]
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
blue492
  • 540
  • 1
  • 6
  • 21
  • Why? What was the problem? Adding `-`? Then `\d{4}`? And the string end anchor? `$`? – Wiktor Stribiżew Jun 11 '21 at 09:29
  • Do you mean like this: RegExp(r'^\d{1,6}[\-]?\d{4}') this dose not worked for me in Flutter. – blue492 Jun 11 '21 at 09:56
  • You must add the whole relevant code to your question. And no, I clearly meant `RegExp(r'^\d{1,6}-\d{4}$')` – Wiktor Stribiżew Jun 11 '21 at 10:03
  • Did you tested that in Flutter like this: because it did worked for me, inputFormatters: [new FilteringTextInputFormatter.allow( RegExp(r'^\d{1,6}-\d{4}') ,], with your solution I can not write any input – blue492 Jun 11 '21 at 11:08
  • *A TextInputFormatter that prevents the insertion of characters matching (or not matching) a particular pattern.* - the validation triggers for each input char, right? That is why it can't work in general. Try a regex that matches all of these as optional chars except the first digit, `RegExp(r'^\d{1,6}(?:-\d{0,4})?$')` – Wiktor Stribiżew Jun 11 '21 at 11:13
  • Or, `RegExp(r'^\d{0,6}(?:-\d{0,4})?$')` – Wiktor Stribiżew Jun 11 '21 at 11:23
  • These two worked well, thank you. – blue492 Jun 11 '21 at 12:11

1 Answers1

3

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563