正则表达式:一个或多个可选参数,但至少有一个

时间:2017-07-21 15:05:23

标签: c# regex

我正在编写一个C#程序,它有许多用户fiels正在进行正则表达式验证。

我找不到在我的正则表达式中包含一个或多个可选参数但至少一个的方法。

我做了以下正则表达式:

^([\" \"]*[\\+\\-][\" \"]*)?((?<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
  • ...

那些最后的代码没有任何“可选字母”,但它们至少需要一个。可能性是:

  • [代码]ë
  • [代码] EA
  • [代码] R
  • [代码] RA
  • [代码]一个

你能帮我吗?

如果您想尝试一下,可以转到https://regex101.com/

我还试图在没有成功的情况下实现这样的事情:Regex with all optional parts but at least one required

我找不到我错过的东西......任何帮助都会很好!

2 个答案:

答案 0 :(得分:2)

试试这个正则表达式:
$query = $this->db->query('SELECT username,useremail FROM tbl_cart where user_id= '.$this->session->userdata('userId').'AND status=1' ); $resultdata['results'] = $query->result_array();

第四个条件由^(?: *[+-]? *[A-Z][0-9b-df-qs-zA-Z]*([re])?(?(1)a?|a))+$处理,这意味着“选择([re])?(?(1)a?|a)e,如果您这样做,请选择r,但如果您没有,请采取强制性a

就像我在评论中所说的那样,你可以用a列出所有可能性,但是如果添加参数,可能性的数量会呈指数增长。

演示here

编辑:接受包含非alphanum char的代码 编辑2:实际上a|e|r|ea|ra应该更好,并且不会成倍增加

答案 1 :(得分:0)

这也有效。

^(?:[ ]*[+-]?[ ]*[A-Z][A-Z0-9]*(?:[er]a?|a))+$

https://regex101.com/r/IYO0Xv/1

详细

 ^ 
 (?:
      [ ]* [+-]? [ ]* [A-Z] [A-Z0-9]* 
      (?:
           [er] a?
        |  a
      )
 )+
 $ 

您要检测的单个错误代码将是这样的

^[A-Z][A-Z0-9]*$

https://regex101.com/r/2caZBS/1