Regex to validate logical && || operators in string

前端 未结 1 638
温柔的废话
温柔的废话 2021-01-12 15:40

I am trying to create a Regex expression to validate logical && || string combonation and its corresponding opening and closing ()

1条回答
  •  广开言路
    2021-01-12 16:22

    I think the reason you are not able to validate expressions without a wrapping () is the wrapping parentheses in your core nesting logic. If you take out the following parentheses I note below, then the other two non-wrapped expressions validate:

    ^(?=^[^()]*\((?>[^()]+|\((?)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\)[^()]*$...
               ^^ remove this                            remove this ^^
    

    Then in order to allow expressions that are not just numerical, you need to replace your restrictive \d with a more liberal definition of what you want to validate, say, [0-9a-zA-Z]:

    ...[(]*\d+[)]*(\s+(&&|\|\|)\s+[(]*\d+[)]*)*$
           ^^ change these expression ^^
    

    So it would become:

    ...[(]*[0-9a-zA-Z]+[)]*(\s+(&&|\|\|)\s+[(]*[0-9a-zA-Z]+[)]*)*$
    

    Demo: http://ideone.com/jwkcpL

    0 讨论(0)
提交回复
热议问题