英文:
need a regex to validate 'earn extra 20%' or 'earn 20% extra'
问题
需要一个正则表达式来验证以下字符串,如下所示。
'Earn extra 20%' - 有效
'Earn 20% extra' - 有效
'earn extra 20%' - 有效
'earn 20% extra' - 有效
'Earn 20' - 有效
'Earn ' - 无效
'20' - 无效
'Earn ^&' - 无效
不应允许使用任何其他特殊字符
- 使用golang 1.19
英文:
Need a regex to validate following strings as mentioned.
'Earn extra 20%' - valid
'Earn 20% extra' - valid
'earn extra 20%' - valid
'earn 20% extra' - valid
'Earn 20' - valid
'Earn ' - Invalid
'20' - Invalid
'Earn ^&' - Invalid
any other special characters should not be allowed
-using golang 1.19
答案1
得分: 4
使用(?i)
(不区分大小写)标志和可选项的替代方案(而不是使用前后查找,go语言不支持):
(?i)earn (\d+%?( extra)?|extra \d+%?)
查看实时正则表达式演示。
查看实时go演示。
英文:
Use the (?i)
(case insensitive) flag and an alternation with optional terms (instead of using look arounds, which go doesn't support):
(?i)earn (\d+%?( extra)?|extra \d+%?)
See live regex demo.
See live go demo.
答案2
得分: -1
尝试这个:
regex := regexp.MustCompile(`^(?=.*\b赚\b|\b赚\b)(?=.*\b\d+\b|%)(?!.*[^a-zA-Z0-9%\s])`)
测试链接:https://regex101.com/r/axGrst/1
英文:
Try this:
regex := regexp.MustCompile(`^(?=.*\bEarn\b|\bearn\b)(?=.*\b\d+\b|%)(?!.*[^a-zA-Z0-9%\s])`)
Testing: https://regex101.com/r/axGrst/1
答案3
得分: -1
请尝试以下内容:
^(?=[a-zA-Z0-9_ ]*(?i)earn[a-zA-Z0-9_ ]*)(?=[a-zA-Z0-9_ ]*(?i)extra[a-zA-Z0-9_ ]*)(?=[a-zA-Z0-9_ ]*20%?[a-zA-Z0-9_ ]*)
这将匹配以下内容:
- 字符串必须包含 earn、extra 和 20
- 20 后面可以有或没有 %
- 其他单词不应包含特殊字符(只允许数字和普通字符)
英文:
Try below,
^(?=[a-zA-Z0-9_ ]*(?i)earn[a-zA-Z0-9_ ]*)(?=[a-zA-Z0-9_ ]*(?i)extra[a-zA-Z0-9_ ]*)(?=[a-zA-Z0-9_ ]*20%?[a-zA-Z0-9_ ]*)
This will match -
- String which must have earn, extra and 20 in string
- With or without % after 20
- Other words should not contain the special character (only numbers and normal characters are allowed)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论