简体   繁体   English

Flutter TextFormField inputFormatters 正则表达式 (RegEx) 不起作用

[英]Flutter TextFormField inputFormatters regular expression (RegEx) doesn't work

I want to have a regular expression in flutter on my TextFormField, that only numbers between -999 & 999 can be put in. When I tested the expression everything worked how I wanted to, but I don't know why I can not write "-" in the TextFormField.我想在我的 TextFormField 上的 flutter 中有一个正则表达式,只能输入 -999 和 999 之间的数字。当我测试表达式时,一切都按我的意愿工作,但我不知道为什么我不能写“ -”在 TextFormField 中。 The maximum numbers and that a number should not start with 0 works perfectly fine, but all the time I try to add a minus it doesn't work.最大数字和一个数字不应该以 0 开头工作得很好,但我一直尝试添加一个减号它不起作用。 I would be thankful for any help!如果有任何帮助,我将不胜感激!

 TextFormField(
              decoration: kTextFieldDecoration,
              style: kCustomNumberBoxTextStyle,
              keyboardType: TextInputType.numberWithOptions(signed: true),
              textAlign: TextAlign.center,
              initialValue: number.toString(),
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    RegExp(r'^-?[1-9]([0-9]{1,2})?')),
              ],
              onChanged: (String newValue) {
                if (newValue != "") {
                  setState(() {
                    number = int.parse(newValue);
                  });
                  widget.onTap(int.parse(newValue));
                }
              },
            ),

Your ^-?[1-9]([0-9]{1,2})?你的^-?[1-9]([0-9]{1,2})? regex makes the initial hyphen optional, which is fine, but the [1-9] part requires a non-zero digit.正则表达式使初始连字符可选,这很好,但[1-9]部分需要一个非零数字。 Moreover, you missed the $ anchor at the end, and the regex can match anything after the third digit.此外,您错过了最后的$锚点,正则表达式可以匹配第三位数字之后的任何内容。

In order to be able to insert a single - , you need to make the digit matching parts optional.为了能够插入单个- ,您需要将数字匹配部分设为可选。

You can thus use您可以因此使用

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

See the regex demo .请参阅正则表达式演示 Details :详情

  • ^ - start of string ^ - 字符串的开头
  • -? - an optional - char - 一个可选的-字符
  • (?:[1-9][0-9]{0,2})? - an optional sequence of - 一个可选的序列
    • [1-9] - a non-zero digit [1-9] - 非零数字
    • [0-9]{0,2} - any zero, one or two digits [0-9]{0,2} - 任何零、一位或两位数
  • $ - end of string. $ - 字符串结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM