Master Yoda
Master Yoda

Reputation: 4422

how to handle new lines in Regular expressions

I have an application that reads codes from a text file written in C#.

The codes will generally follow the same pattern each time

example:

QUES10100

From what i have written so far this results in the regular expression looking like this:

string expr = "^[A-Z]{4}[0-9]{5}$";

The question then is when the codes are read from a text file ( One per new line ) the codes have the \r new line character appended. This is from placing a breakpoint on to see what was really being passed through.

What am i missing from the expression provided above?

Also if i am adding the codes individually the /r characters are not appended so its fine, in this case i would need an or operand in there somewhere.

Summary

What I have so far: ^[A-Z]{4}[0-9]{5}$

What I need: ^[A-Z]{4}[0-9]{5}$ OR ^[A-Z]{4}[0-9]{5}$ with /r characters accounted for.


Thanks, any clarifications please let me know as my experience with REGEX is very limited.


Update

string expr = "^[A-Z]{4}[0-9]{5}";

Regex regex = new Regex(expr , RegexOptions.IgnoreCase);
Match match = regex.Match( code );

if (!match.Success) //Pattern must match
{
  MessageBox.Show("Code does not match the necessary pattern");
  return false;
}

 return true;

Upvotes: 0

Views: 75

Answers (2)

npinti
npinti

Reputation: 52195

If you have no control over how are the strings being read, you could also take a look at the String.Trim(char\[\] values) method, which would allow you to sanitize your string before hand:

Something like the below:

string str = "....".Trim(new char[] {'\r', '\n'});

This is usually recommended (since almost anything is better than regex :)).

Then you would feed it to the regular expression you have built.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59292

Why do you want to use regex for that? Use File.ReadLines and use the regex for validation.

foreach(string line in File.ReadLines(@"c:\file path here")) {
    if (Regex.Test(expr, line)) {
        Console.WriteLine(line);
    }
}

Upvotes: 2

Related Questions