首页 > 解决方案 > 正则表达式限制可选的出现

问题描述

我想允许任何字母或数字,如果使用,#只允许在开头只出现一次,例如#{1}. 并保留我在 characters 表达式中已有的限制^<>@.\/()

这是我的正则表达式:

/^[#?a-zA-z0-9][^<>@.\/()]+/g

我希望这个正则表达式通过一些用例:

##msidfipds - fail (2 of #)
fdsfsdfd#1m - fail (# not 1st character)
vcvxcvxcvxc - pass
#fdfdsfsdfs - pass

小部件的用例TextField

TextField(
    inputFormatters: <TextInputFormatter>[
           FilteringTextInputFormatter.allow(RegExp(r'^#?[a-zA-Z0-9][^#<>@.\/()]*$')),
   ],
   autofocus: true,
   enableInteractiveSelection: true,
   keyboardType: TextInputType.text,
   decoration: InputDecoration(
       fillColor: Colors.transparent,
       border: InputBorder.none,
       hintText: 'Search',
   ),
   textAlign: TextAlign.center,
   style: TextFieldStyle,
),

标签: regex

解决方案


使用起始锚点,然后使用可选量词:

/^#?[a-zA-Z0-9][^<>@.\/()]+/g

这将确保如果出现 octothorpe,它必须出现在字符串的开头。


推荐阅读