I want to allow this kind of input to my text field:
123
*123#
*123*4#
so I created and tested RegExr website this regex:
\**\d \**\d \#?
but when i try to type nothing is typed in the text field
code of using:
...
keyboardType = TextInputType.phone;
// to allow digits with asterik and hash
final regex = RegExp(r'\**\d \**\d \#?');
inputFormatters = [FilteringTextInputFormatter.allow(regex)];
return TextField(
...
keyboardType: keyboardType,
inputFormatters: inputFormatters,
);
CodePudding user response:
You can use
^\*?(?:\d \*?(?:\d #?)?)?$
See the regex demo.
Details:
^- start of string\*?- an optional*char(?:\d \*?(?:\d #?)?)?- an optional sequence of\d- one or more digits\*?- an optional*
(?:\d #?)?- an optional sequence of one or more digits and an optional#char$- end of string.
CodePudding user response:
If you also want to match a variation with a single digit like *1# you might use a negative lookahead excluding what can not be present:
^(?!.*\*[*#]|\d*#$)[*\d]*#?$
Explanation
^Start of string(?!Negative lookahead, assert what to the right is not.*\*[*#]Match either**or*#|Or\d*#$Match optional digits and#at the end of the string
)Close lookahead[*\d]*#?Match optional*chars or digits and optional#$End of string
See a regex demo.
