0

I am new to using Regex and was struggling with a problem. I have got to a certain point and I am stuck, I can't figure out how to 'ignore' or not match a pin which has a line break in it which is causing the code to fail the test.

using System;
using System.Text.RegularExpressions;

public class Pin
{
  public static bool ValidatePin(string pin){
     string pattern = "^([0-9]{4}|[0-9]{6})$";
     Regex reg = new Regex(pattern); 
     Match match = reg.Match(pin);
    
     if (match.Success) {
        return true;
     } else {
        return false;
}

I have the regular expression above, how would I implement it so that when it tries to match a pin with the line break it returns "FALSE". The failed test pin was: "1234\n".

hawks
  • 49
  • 5
  • Does this answer your question? [How to completely ignore linebreak and tab in RegEx?](https://stackoverflow.com/questions/4654006/how-to-completely-ignore-linebreak-and-tab-in-regex) – lorenzozane Nov 11 '20 at 22:58
  • @LorenzoZane: while I'm pretty sure this question is a duplicate, your proposed one looks like the exact opposite of what this question is asking. The regex is already ignoring the linebreak and returning a match in spite of its presence; the OP wants it to _not_ do that. – Peter Duniho Nov 11 '20 at 23:01
  • See [this answer](https://stackoverflow.com/a/4123738) in the duplicate. It addresses the general case and your scenario directly. – Peter Duniho Nov 11 '20 at 23:04

1 Answers1

1

Replace $ (it can match before the line feed symbol at the string end position) with \z, the very end of string, use

string pattern = @"\A([0-9]{4}|[0-9]{6})\z";

\A is also useful instead of ^ so as to always match the start of string (if that's your intention).

See proof.

Explanation

--------------------------------------------------------------------------------
  \A                       the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [0-9]{4}                 any character of: '0' to '9' (4 times)
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    [0-9]{6}                 any character of: '0' to '9' (6 times)
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \z                       the end of the string
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37