C # Regular Expression

I have a text file ( .txt

) that has some expressions and I want to replace the invalid expression with ...... let's say zero.

An invalid expression is an expression containing 1+3^4^5

or 10+3+4*5+2^5^6^7

, that is, an expression cannot contain number^number^number^...

, it can only contain number^number

.

I understand that the best way to do this is to use Regex, but I don't know how to write this in regex.

+3


source to share


2 answers


A regular expression that will detect multiple degrees,

(\d+\^){2,}

      

( {2,}

means two or more times in a row)


Run 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);
        }
    }
}

      

The output was:



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

      

Couldn't replace trailing \ d but it works. You can capture the trailing \ d with the following regex correction:

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

      


If you want to destroy all expression containing double cardinality, just use

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

      

in your expresion replacement. .*

on either side will absorb the entire string surrounding double the power when the replacement occurs.

+7


source


Here's the regex for that:



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

...

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

      

+2


source







All Articles