1

Goal is to take in a text file, normalize it down to only having all upper case letters, remove all special characters, and turn any new line into a single space.

This is my current messy code to do it, and as far as I can tell it does work.

public string readTextFile(string fileName)
{
    Regex rgx = new Regex("[^A-Z ]");
    string txtFile = File.ReadAllText(fileName).ToUpper();

    txtFile = Regex.Replace(txtFile, @"\s+", " ", RegexOptions.Multiline);
    return rgx.Replace(txtFile, "");
}

Looking for anyone to help clean this code up, improve efficiency, and possibly combine my regex statements to one.

5
  • 2
    you can't really combine them because they are doing two different operations. Commented Oct 28, 2015 at 20:06
  • 1
    do you call this messy?! this isnt really messy if you good format your code as i did it for you ;) you can also define regexes behind each other to make it less seem messy Commented Oct 28, 2015 at 20:09
  • what is fullBook here? Commented Oct 28, 2015 at 20:10
  • 1
    turn any new line into a single space - \s+ matches 1 or more any whitespace. If you need to match newlines only, use [\r\n]+. How many files do you handle? 1, 10, 100000? If more than a hundred, I suggest that you should avoid declaring the Regex object every time, declare it outside the method (best as private static readonly field). Commented Oct 28, 2015 at 20:12
  • see about this override replace method Commented Oct 28, 2015 at 21:24

1 Answer 1

1

You can combine your regex, and use Replace method with MatchEvaluator like this

public string readTextFile(string fileName)
{
    Regex rgx = new Regex("");
    string txtFile = File.ReadAllText(fileName).ToUpper();

    txtFile = Regex.Replace(txtFile, @"(\s+)|([^A-Z ])", 
                m=> m.Groups[2].Success ? string.Empty : " ",
                RegexOptions.Multiline);
    return txtFile;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.