regex - 正则表达式限制可选的出现
问题描述
我想允许任何字母或数字,如果使用,#
只允许在开头只出现一次,例如#{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,
),
解决方案
使用起始锚点,然后使用可选量词:
/^#?[a-zA-Z0-9][^<>@.\/()]+/g
这将确保如果出现 octothorpe,它必须出现在字符串的开头。
推荐阅读
- flutter - 如何使用未来
在小部件中 - asp.net - How to extend ASP.Net Web Forms app adding Blazor?
- python - 如何从熊猫中的文件中读取数据
- git - 如何过滤分支保留重命名文件夹的历史记录?
- reactjs - 为滑块赋值
- google-app-engine - 来自 App Engine 的简单 Google Drive API 文件查询的 400-500 毫秒延迟
- javascript - 匹配特定的网址格式
- javascript - 如何使水平条形图的高度灵活,以便在添加新数据时调整大小?
- amazon-web-services - SSH 拒绝规则允许我使用 SSH?
- git - Git拒绝使用远程分支执行活动