I have an arithmetic expression

```
string exp = "((2+3.1)/2)*4.456";
```

I want to validate by using regular expression. The expression can only have integers, floating point numbers, operands and parenthesis.

How can i generate regular expression to validate please help or suggest any other way to validate that string.

You could write a simple lexer in F# using fslex/fsyacc. Here is an example which is very close to your requirement: http://blogs.msdn.com/b/chrsmith/archive/2008/01/18/fslex-sample.aspx

Using Perl/PCRE we could verify such simple arithmetic expressions with help of a pattern structured like:

```
expr = pnum ( op pnum )*
pnum = num | \( expr \)
```

Where `num`

and `op`

defined as required. For example:

```
num = -?+\d++(?:\.\d++)?+
op = [-+*/]
```

Which would give us the following working expression:

```
(?x)^ (?&expr) $
(?(DEFINE)
(?<expr> (?&pnum) (?: (?&op) (?&pnum) )*+ )
(?<pnum> (?> (?&num) | \( (?&expr) \) ) )
(?<num> -?+\d++(?:\.\d++)?+ )
(?<op> [-+*/] )
)
```

But such expressions could not be used with .NET regex as it does not support (recursive) suppatern calls `(?&name)`

. Instead .NET regex lib offers us its special feature: balancing groups.

With balancing groups we could rewrite the required recursive call used in `pnum`

, and use a structure like this instead:

```
expr = pnum ( op pnum )* (?(p)(?!))
pnum = (?> (?<p> \( )* num (?<-p> \) )* )
```

What we've done here is to allow any number of optional opening and closing paranthesis before and after every number, counting the total number of open parentheses `(?<p> \( )`

, subtracting closing parentheses from that number `(?<-p> \) )`

and at the end of the expression make sure that the number of open parentheses is 0 `(?(p)(?!))`

.

(I believe this is equivalent to the original structure, altho I haven't made any formal proof.)

Resulting in the following .NET pattern:

```
(?x)
^
(?> (?<p> \( )* (?>-?\d+(?:\.\d+)?) (?<-p> \) )* )
(?>(?:
[-+*/]
(?> (?<p> \( )* (?>-?\d+(?:\.\d+)?) (?<-p> \) )* )
)*)
(?(p)(?!))
$
```

```
using System;
using System.Text.RegularExpressions;
namespace RegexTest
{
class Program
{
static void Main(string[] args)
{
var expressions = new string[] {
"((2+3.1)/2)*4.456",
"1",
"(2)",
"2+2",
"(1+(2+3))",
"-2*(2+-2)",
"1+(3/(2+7-(4+3)))",
"1-",
"2+2)",
"(2+2",
"(1+(2+3)",
};
var regex = new Regex(@"(?x)
^
(?> (?<p> \( )* (?>-?\d+(?:\.\d+)?) (?<-p> \) )* )
(?>(?:
[-+*/]
(?> (?<p> \( )* (?>-?\d+(?:\.\d+)?) (?<-p> \) )* )
)*)
(?(p)(?!))
$
");
foreach (var expr in expressions)
{
Console.WriteLine("Expression: " + expr);
Console.WriteLine(" Result: " + (regex.IsMatch(expr) ? "Matched" : "Failed"));
}
}
}
}
```

Output:

```
Expression: ((2+3.1)/2)*4.456
Result: Matched
Expression: 1
Result: Matched
Expression: (2)
Result: Matched
Expression: 2+2
Result: Matched
Expression: (1+(2+3))
Result: Matched
Expression: -2*(2+-2)
Result: Matched
Expression: 1+(3/(2+7-(4+3)))
Result: Matched
Expression: 1-
Result: Failed
Expression: 2+2)
Result: Failed
Expression: (2+2
Result: Failed
Expression: (1+(2+3)
Result: Failed
```

Similar Questions

I know I can use preg_match but I was wondering if php had a way to evaluate to a regular expression like: if(substr($example, 0, 1) == /\s/){ echo 'whitespace!'; }

I am using this regular expression for validating email address for example: ValidationExpression=\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* and now I want to write a validation expression for no

I'm trying to write a regular expression for strings that are numbers in JSON. I'm still new to writing Regular expressions, I found a diagram of a machine for JSON numbers here , but I'm not sure ho

In my current regular expression, I am negating digits: $(function(){ $(#somewhat).bind(keyup, function(event) { var regex = /^[\D]*$/; alert(regex.test($(#somewhat).val())); }); }); What I hav

I'm trying to get a regular expression to work and I'm having problems: I want to match everything that starts with __(' or __( and ends with ') or ) I tried with /__\(['][^']*[']\)/g and /__

I am working with a regular expression that would check a string,Is it a function or not. My regular expression for checking that as follows: regex=r' \w+[\ ]*\(.*?\)*' It succefully checks whether t

please help me decipher the regular expression- '!_[$0]++' It is being used to get a MSISDN (one at a time from a file containing list of MSISDN starting with zero )by the following usage: awk '!_[$0

Using regular expression, how would I validate a date to make sure it is only entered in this format: mm/dd/yyyy? If anyone is interested, I'm using validates_format_of :date_field, :with => // in

I'm currently working on a library that simplifies creating regular expression patterns. To generate the most legible patterns, I'd like to simplify quantifiers where possible. Assume the following su

I am trying to solve an arithmetic expression in prolog (implementation - eclipse prolog). The arithmetic expression to be solved is like this: A * (C + B * X) + D * X = E X is the value to be comput

I need to be able to create a regular expression that will search through any string in Java and match this particular expression. Reg Match: ./ ADD NAME= <--- I need to match this regular expressi

i'm not very good at regular expressions.. how would I add a .tile (without quotes) to this regular expression pattern: private static final Pattern JSP_PathPattern = Pattern.compile((.+\\/)(\\w+)(

Simple arithmetic expression enclosed in '((' evaluates to true when inside compound conditional expression '[[' HAVE_SRC=1 [[ (( $HAVE_SRC == 1 )) && -d $( pwd ) ]] echo $? # returns 0 =>

I m uaing following regular expression for validating decimal or numeric (18,3) numbers, it does disllow users from entering more than 1 decimal points and all that <asp:RegularExpressionValidator

I know how to convert regular expression into FSM but not exactly sure how to reverse it. what would the regular expression for this example be?

Possible Duplicate: Regular expression to check if a given password contains at least one number and one letter in c#? I need to create regular expression for password with following requirement: Mi

Is there a way to test if a regular expression contains another regular expression? For example: RegEX1 = a.*b; RegEx2 = a1.*b; RegEX1 contains RegEX2. As far as I know - this can't be done,

I need to validate a text based upon a regular expression in javascript. My regular expression is working fine but but can't find out why it is not working in java script. The regular expression is th

Does anyone know how to find regular expression string from javascript code? e.g. var pattern = /some regular expression/; Is it possible to to with regular expression :) ?

Is there any formal documentation of how to implement your own regular expression library? What formal documentation, if any, did the makers of the exisiting regular expression libriaries base their c

I needed a regular expression for a mathematical expression, which should satisfy the following conditions explained in this SO Question which was asked by me. It worked fine with this expression But

My regular expression goal: If the sentence has a '#' in it, group all the stuff to the left of the '#' and group all the stuff to the right of the '#'. If the character doesn't have a '#', then just

I am using Asp.Net/C# in my project.In one of my forms I am using Regular Expression Validator to validate an email address.I searched for some examples for validating email.I found this \w+([-+.']\w+

I have this code with this regular expression: string lPattern = \\S*[a-zA-Z]+\\S*; System.Text.RegularExpressions.Regex lRegex = new System.Text.RegularExpressions.Regex(lPattern); if (!lRegex.IsMa

Hey guys am new to regular expression i have found a regular expression like this .. preg_match(/^(1[-\s.])?(\()?\d{3}(?(2)\))[-\s.]?\d{3}[-\s.]?\d{4}$/,$number) preg_match(/^ (1[-\s.])? # optional

I want to use regular expression in JavaScript for form input validation. These is a string which should not have either < , > or any specific set of chars which I mention. The test should pass

I'm trying to match a valid Ip address using a regular expression. I have an expression bu the problem is I'm not able to understand grep behavior. to match numbers in the range 0-255 I did : echo 15

I am developing a http robot, and I developed this regular expression (((?:f|ht)tp(?:s)?\\://)?|www)([^/]+) to detect and extract the hostname from a link (href). Now I put here the results of the tes

I'm trying to learn flex and having trouble with a regular expression to catch comments. Assuming a comment begins with // and runs to the end of the line, I would like the program to recognize the en

I need a regular expression that matches the shortest string between $ and |$ Example test string: 'bla bla$bla bla $bla bla|$bla bla bla' regular expression: /\$(.*?)\|\$/ i get 'bla bla $bla b

I have the following string: 30.03.2014 And I need a regular expression, which gives me this part: 03 I am not allowed to use lookahead, because it is not supported. The expression should just retur

I have used the following pattern for the regular expression for the phone number pattern=[0-9 -+]+$; The phone number may contain numbers, hyphen(-), space and plus(+). It works when i use number

I have written the following regular expression to return everything except alphabets & letters. However this regular expression returns nothing. What can be the regular expression for such case?

What is the regular expression for the language 0m1n where m+n is even?

This is an interview question, for which I did not find any satisfactory answers on stackoverflow or outside. Problem statement: Given an arithmetic expression, remove redundant parentheses. E.g. ((

Hey everyone, I'm having a minor difficulty setting up a regular expression that evaluates a sentence entered by a user in a textbox to keyword(s). Essentially, the keywords have to be entered consecu

Im searching for the regular expression - .(conflicted copy.. I wrote the following code for this String str = 12B - (conflicted copy 2013-11-16-11-07-12); boolean matches = str.matches(.*(confl

I need a Java regular expression, which checks that the given String is not Empty. However the expression should ingnore if the user has accidentally given whitespace in the beginning of the input, bu

I want the regular expression to extract the &[1], &[2},&[3],&[4] values from the following string, with comma delimited. var str = Sum({[Account].&[1]+[Account].&[2]+[Account

I was wondering, how do I create create a regular expression that allows me to use something akin an or statement. For example, ^\w+? [\s?] OR [\\w\\W]*?]$ where the brackets represent the conditi

I have this regular expression in objective-c NSString* searchString = [searchBlock stringByReplacingOccurrencesOfString:@<(.*?)> withString:@ options: NSRegularExpressionSearch range:NSMak

Basically I am looking for a regular expression for phone numbers. Inputs can be: 009133434343443434 +92333232323232 0223323232 0345* 021* What I have tried ^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0

I have been finding some articles and post which suggest not to use the regular expression to validate user data. I am not sure of all the things but i usually find it in case of email address verific

I need help on regular expression on the condition (4) below: Begin with a-z End with a-z0-9 allow 3 special characters like ._- The characters in (3) must be followed by alphanumeric characters, and

How would you efficiently (optimizing for runtime but also keeping space at a minimum) parse and evaluate a single digit arithmetic expression in Java. The following arithmetic expressions are all val

In Java's regular expression, I want to match any sentence that contains the word Mary and the word are in that order, but DOES NOT contain Bob in between Mary and are. Eg: Mary and Rob are

I have this regular expression: ^(10)(1|0)(.)(.)(.)(.{18})((AB[^|]*)\||(AQ[^|]*)\||(AJ[^|]*)\||(AF[^|]*)\||(CS[^|]*)\||(CR[^|]*)\||(CT[^|]*)\||(CK[^|]*)\||(CV[^|]*)\||(CY[^|]*)\||(DA[^|]*)\||(AO[^|]*)

I have been wondering about the performance of regular expression implementations lately, and have had a hard time coming up with much useful information. Its easy enough to benchmark browser/javascr

I need to write regular expression that will match any pair of tags <(.*?)>.*?</\1> but only if there is no other pair tags between them. Tag names are variable length.

Hi I need a regular expression that'll give me something like this part ./something\, [something.sh from something like this string (./something\, [something.sh, [./something\, [something.sh]