开发者

Regular expression to match digits and basic math operators

I need a开发者_运维知识库 regular expression that will match 0-9, (,),+,-,* and /.


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>)?


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]+)


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 *


[\d\(\)\+\-\*\/\.]


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.


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-9\(\)\+\-\*\./\"]


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

^[0-9+\-*\/\(\)]*$


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-9()+\-*.\/]*$

https://regex101.com/r/377yXA/1

This regex worked for me

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜