Home > front end >  Merging multiple RegExps in Dart
Merging multiple RegExps in Dart

Time:04-03

In a TextFormField in Flutter I want to use multiple inputFormatters. For example, it could look like this:

inputFormatters: <TextInputFormatter>[
  FilteringTextInputFormatter.allow(RegExp('[a-zA-ZäöüßÄÖÜ]')),
  FilteringTextInputFormatter.allow(RegExp('[0-9]')),
]

However, if I have specified both FilteringTextInputFormatters and both allow different characters, then I can't enter anything at all. Therefore, I have to put both in one FilteringTextInputFormatter. So the question is how I can merge the two RegExps without having to rewrite each combination, so I would like to have something like regExp1 regExp2. Is this possible in some way or do I have to rewrite each RegExp?

CodePudding user response:

For combining 2 or more Regular Expressions we can use '|'.

Here you can change your code like this:

FilteringTextInputFormatter.allow(RegExp('[a-zA-ZäöüßÄÖÜ]|[0-9]'))

It works perfectly. If helped don't forgot to do the thing. Thanks

CodePudding user response:

To merge multiple RegExps in the Dart just merge their patterns.

void main() {
 var a = RegExp('[0-9]');
 var b = RegExp('[A-Z]');
 var c = RegExp(a.pattern   b.pattern);
 
 print(a); // RegExp/[0-9]/
 print(b); // RegExp/[A-Z]/
 print(c); // RegExp/[0-9][A-Z]/
}

Function:

RegExp mergeRegExps(List<RegExp> regExps) {
  return regExps.reduce((a, b) => RegExp(a.pattern   b.pattern));
}
  • Related