Regular expression to match digits and basic math operators

前端 未结 9 1854
孤城傲影
孤城傲影 2020-12-03 05:49

I need a regular expression that will match 0-9, (,),+,-,* and /.

相关标签:
9条回答
  • 2020-12-03 06:49
    [0-9\(\)\+\-\*\./\"]
    
    0 讨论(0)
  • 2020-12-03 06:50

    It looks like you might be trying to match numeric expressions like 5+7-3.

    This should match them :

    ([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])+([-+]?[0-9]*\.?[0-9]+)
    
    0 讨论(0)
  • 2020-12-03 06:52

    The accepted answer can't handle a lot of basic cases. This should do the job:

    ^([-+]? ?(\d+|\(\g<1>\))( ?[-+*\/] ?\g<1>)?)$
    

    Explaination:

    We want to match the entire string:

    ^...$
    

    Expressions can have a sign:

    [-+]? ?
    

    An expression consists of multiple digits or another valid expression, surrounded by brackets:

    (\d+|\(\g<1>\))
    

    A valid expression can be followed by an operation and another valid expression and is still a valid expression:

    ( ?[-+*\/] ?\g<1>)?
    
    0 讨论(0)
提交回复
热议问题