Regular expression to match digits and basic math operators

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

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

相关标签:
9条回答
  • 2020-12-03 06:26

    I think you are looking for character classes

    [0-9()+\-*/.]
    

    This should match a word that contains any number from 0 to 9 or ( ,),+,- ,/ or *

    0 讨论(0)
  • 2020-12-03 06:29
    regex  = '(?:[0-9 ()]+[*+/-])+[0-9 ()]+'
    string = 'mig 2*7 5+ 43 asf 4 3+32 *33 as 0 fa 3 5+9 m (3 + 5) - 9*(99)'
    re.findall(regex, string)
    # answer
    # [' 2*7 5+ 43 ', ' 4 3+32 *33 ', ' 3 5+9 ', ' (3 + 5) - 9*(99)'] 
    
    0 讨论(0)
  • 2020-12-03 06:34

    This regex helps me, just take a note here maybe it helps others.

    ^[0-9+\-*\/\(\)]*$
    
    0 讨论(0)
  • 2020-12-03 06:35

    If you need a regex to match an arithmetic expression like this: 3+2-24*2/2-1 you can try this:

    String reg1="([0-9]+[\\+\\-\\*\\/]{1}[0-9]+)+([\\+\\-\\*\\/]{1}[0-9]+)*";
    

    You can add the bracket where do you want if you'll edit this regex.

    0 讨论(0)
  • 2020-12-03 06:35

    This works for mathematical expression with 4 decimal places:

    ^([-+]? ?(\d+(\.\d{0,4})?|\(\g<1>\))( ?[-+*\/] ?\g<1>)?)$
    

    It's inspired in base of @ndnenkov answer.

    I hope that can be useful for someone.

    0 讨论(0)
  • 2020-12-03 06:41
    [\d\(\)\+\-\*\/\.]
    
    0 讨论(0)
提交回复
热议问题