Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx -- Quantifier {x,y} following nothing error

I am very new to RegEx -- so can someone please help me figure out what exactly is going wrong here?

I have this code:

       string regPattern = "*[~#%&*{}/<>?|\"-]+*";
       string replacement = "";
       Regex regExPattern = new Regex(regPattern);

Yet, when my app hits the regExPattern line, i get an ArgumentException -- Quantifier {x,y} following nothing error.

Can someone help?

EDIT: I need to pass this pattern into a foreach loop like so:

    if (paths.Contains(regPattern))
        {
            foreach (string files2 in paths)
            {
                try
                {
                    string filenameOnly = Path.GetFileName(files2);
                    string pathOnly = Path.GetDirectoryName(files2);
                    string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
                    string sanitized = Path.Combine(pathOnly, sanitizedFileName);
                    //write to streamwriter
                    System.IO.File.Move(files2, sanitized);

                }
                catch (Exception ex)
                {
                    //write to streamwriter

                }
            }
        } 
        else
        { 
        //write to streamwriter

        }

How do i define the pattern if it is being passed into this loop?

like image 995
yeahumok Avatar asked Jun 28 '10 19:06

yeahumok


2 Answers

Update: after reading the comment to the question I think you want simply this:

s = Regex.Replace(s, "[~#%&*{}/<>?|\"-]+", "");

Old answer: I guess when you write * you are thinking of wildcards such as those you would enter at a shell:

*.txt

This is not how the * works in regular expression syntax. What you probably want instead is .*:

".*[~#%&*{}/<>?|\"-]+.*"

The . means "any character" and the * means "zero or more of the previous".

Inside the character class [...] the * loses its special meaning and becomes a literal character so it does not need to be escaped. Escaping it unnecessarily inside the character class will not cause any harm and some people find it easier to read.

like image 113
Mark Byers Avatar answered Sep 18 '22 02:09

Mark Byers


The * is a quantifier meaning "zero or more times" (same as {0,}). You'll have to escape it using a backslash like this: \*

like image 38
Daniel Egeberg Avatar answered Sep 21 '22 02:09

Daniel Egeberg