regex - 您将如何为输入验证编写正则表达式以使某些符号不能重复?
问题描述
我正在尝试编写一个正则表达式来防止某些用户在数学表达式中输入。(例如,“1+1”是有效的,而“1++1”应该是无效的)可接受的字符包括*digits 0-9* (\d works in lieu of 0-9), + - # / ( ) and white-spaces.
我试图组合一个正则表达式,但我在 python 正则表达式语法中找不到任何可以验证的东西(或者因此在一起输入时使某些字符无效。
(( is ok
++, --, +-, */, are not
我希望有一种简单的方法可以做到这一点,但我预计如果没有,我将不得不为我不想允许在一起的每个可能的字符组合编写正则表达式。
我试过了:
re.compile(r"[\d\s*/()+-]")
re.compile(r"[\d]\[\s]\[*]\[/]\[(]\[)]\[+]\[-]")
如果有人输入“1++1”,我希望能够使表达式无效
编辑:Someone suggested the below link is similar to my question...it is not :)
解决方案
也许一种选择可能是检查字符串是否有不需要的组合:
[0-9]\s*(?:[+-][+-]|\*/)\s*[0-9]
例如
pattern = r"[0-9]\s*(?:[+-][+-]|\*/)\s*[0-9]"
strings = [
'This is test 1 -- 1',
'This is test 2',
'This is test 3+1',
'This is test 4 */4'
]
for s in strings:
res = re.search(pattern, s)
if not res:
print("Valid: " + s)
结果
Valid: This is test 2
Valid: This is test 3+1
推荐阅读
- c# - 第一次连接后的 localhost Websockets 404
- visual-studio-code - 使用 Mac 的 VSCode 中的蓝色水平线
- python - 来自 Webelement 的文本(Selenium + Python)
- python - 在使用 .partition 的 selenium 中,我的代码只打印子字符串之前的内容,而不是子字符串之后的内容
- python - 用于修补子分段的 AWS X-Ray Python 开发工具包元数据
- c# - C# MSBuild 不包括 NuGet 包(适用于 Visual Studio 17)
- azure - 在 Azure Front Door 中重写 URL 路径 - 错误 HTTP 404
- python - 保留字符串 Pandas 中的数值
- c# - LINQ 不返回数据
- arrays - Django Queryset 按确切字符串过滤数组字段