我正在编写一个 C# 程序,其中有许多用户字段具有正则表达式验证。
我找不到一种方法来在我的正则表达式中包含一个或多个可选参数,但至少一个。
我制作了以下正则表达式:
^([\" \"]*[\\+\\-][\" \"]*)?((?<leftoperand>[A-Z]+[A-Z0-9]*)[er]?[a]? *)(([\" \"]*[\\+\\-][\" \"]*)+((?<rightoperand>[A-Z]+[A-Z0-9]*)[er]?[a]? *))*[\" \"]*$
它允许我验证公式。这个公式有特定的规则,其中大部分我可以验证:
1. The formula can starts with a '+' or '-' sign, or white spaces
2. The formula contains only "codes" starting with at least one capital letter, then followed by the rest of the code, and can include other capital letters or numbers
3. They can be as many codes in a formula as one wishes
4. Codes ends up with optionals parameters.
First : either a lowercase 'e' or 'r',
Then : an optional 'a'
BUT it contains at least one
我正在努力解决第四条规则......
正确代码示例:
- D11e
- D122ea
- B9r
- TOTFRra
- APUL2a
正确公式示例:- D11e + D121ea - D122ra
我已经可以管理的不正确代码示例:
- d122ea(以小写字符开头)
- 9r(以数字开头)
- TOTFRer(包含“e”和“r”)
- APUL2era(包含所有可选参数)
我想要检测的不正确代码示例:
- D11
- D122
- ...
最后的代码没有任何“可选字母”,但它们至少需要一个。可能性是:
- [代码]e
- [代码]ea
- [代码]r
- [代码]ra
- [代码]a
你能帮我一下吗?
如果你想尝试一下,可以去https://regex101.com/
我也尝试过实现类似的东西但没有成功:Regex with all optional parts but at least one required
我只是找不到我缺少的东西...任何帮助都会很好!
最佳答案
尝试这个正则表达式:
^(?: *[+-]? *[A-Z][0-9b-df-qs-zA-Z]*([re])?(?(1)a?|a))+$
第四个条件由 ([re])?(?(1)a?|a)
处理,这意味着“采用可选的 e
或 r
,那么如果您这样做了,则采用可选的 a
,但如果您没有这样做,则采用强制性的 a
"
正如我在评论中所说,您可以使用 a|e|r|ea|ra
之类的内容列出所有可能性,但如果添加参数,可能性的数量将呈指数级增加。
演示 here
编辑:接受包含非字母字符的代码。
编辑2:实际上[er]?a|[er]
应该更好,并且不会呈指数增长
关于c# - 正则表达式 : one or many optional parameters but at least one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240958/