hyperN
hyperN

Reputation: 2754

C# Regular expression

I have plain text file (.txt) which has some expressions and I want to replace invalid expression with... ...let's say zero.

An invalid expression is expression which contains 1+3^4^5 or 10+3+4*5+2^5^6^7, i.e. an expression can't contain number^number^number^..., it can only contain number^number.

I understand that best way to do this is to use Regex but I dont know how to write this in regex.

Upvotes: 3

Views: 459

Answers (2)

Alain
Alain

Reputation: 27220

The regular expression that will detect multiple powers is

(\d+\^){2,}

({2,} means two or more times in a row)


Just ran the following Test:

using System;
using System.Text.RegularExpressions;
namespace SampleNamespace
{
    public class SampleClass
    {
        public static void Main()
        {
            string line = "1+3^4^5  10+3+4*5+2^5^6^7";              
            System.Console.WriteLine(line);
            line = Regex.Replace(line, @"(\d+\^){2,}", "0");
            System.Console.WriteLine(line);
        }
    }
}

Output was:

>RegexTest.exe
1+3^4^5  10+3+4*5+2^5^6^7
1+05  10+3+4*5+07

It failed to replace the trailing \d but it does work. You can grab the trailing \d with the following correction to the regex:

(\d+\^){2,}\d+

If you want to wipe out the entire expression that contains a double power just use

.*(\d+\^){2,}.* 

in your replace expresion. The .* on either side will swallow up the entire string surrounding the double power when a replacement takes place.

Upvotes: 7

Ry-
Ry-

Reputation: 224886

Here's a regular expression for that:

Regex re = new Regex(@"(\d+\^){2}");

...

if(re.IsMatch(myData)) {
    // It's not valid
}

Upvotes: 2

Related Questions