需要一个正则表达式来验证 ‘earn extra 20%’ 或 ‘earn 20% extra’。

huangapple go评论64阅读模式
英文:

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_ ]*)

这将匹配以下内容:

  1. 字符串必须包含 earn、extra 和 20
  2. 20 后面可以有或没有 %
  3. 其他单词不应包含特殊字符(只允许数字和普通字符)
英文:

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 -

  1. String which must have earn, extra and 20 in string
  2. With or without % after 20
  3. Other words should not contain the special character (only numbers and normal characters are allowed)

huangapple
  • 本文由 发表于 2023年6月27日 14:54:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76562288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定