-4

I am new to regex and I am burning hours just to get it right. I need to allow these patterns

NPA-XXX-XXXX
(NPA) XXX-XXXX
NPAXXXXXXX

where NPA = numbers 0 to 9 and X is also any number 0 to 9

so this is valid

123-456-7890
1234567890
(123) 456-7890

but not this

(123)-456-7890   // because there is a dash after closing parenthesis
(123)456-7890    // because there is no space after closing parenthesis
QWE-456-7890  // because there are one or more alpha characters

I use this

Regex r = new Regex(@"^?\(?\d{3}?\)??-??\(?\d{3}?\)??_??\(?\d{4}?\)??-?$");

from System.Text.RegularExpressions

What would be the regular expression that would match the valid?

BlackPearl
  • 1,662
  • 1
  • 8
  • 16
Alexander
  • 1,729
  • 3
  • 19
  • 36
  • It would help us if you showed some of the regices that you've tried so that we can help fine-tune them. Likewise, we'd probably want to know what particular regex library you're using since syntax may differ subtly. – nanofarad Jan 16 '20 at 00:44
  • You should read [this meta Q&A](https://meta.stackoverflow.com/questions/285733/should-give-me-a-regex-that-does-x-questions-be-closed) to understand what the SO communiity thinks of "give me a regex" questions. However, I think you may have gotten a raw deal here ... since you seem to have made an attempt to work it out for yourself. – Stephen C Jan 16 '20 at 00:51
  • Hint: one problem in your attempt is that `(` and `)` are regex meta characters and need to be escaped to match literally. – Stephen C Jan 16 '20 at 00:56
  • 1
    _"I think you may have gotten a raw deal here"_ -- I disagree. _"you seem to have made an attempt"_ -- an actual attempt would involve at least some minimal effort to research existing solutions, and yet there's zero evidence in the question that they in fact did. And it seems very unlikely to me that there's anything so novel about this OP's need that nothing that exists on Stack Overflow already has any use or relevance to the question. – Peter Duniho Jan 16 '20 at 04:13

1 Answers1

0

One way to look at this:

  • all numbers end in XXX-XXXX, with the - being optional, so that's d{3}\-?\d{4}
  • numbers start with either (NPA) or NPA-, with the - being optional, so that's \(\d{3}\) (ending in a space) or \d{3}

Since you can 'or' parts of a regex together with (a|b), the whole regex becomes:

(\(\d{3}\) |\d{3}\-?)\d{3}\-?\d{4}

Note that \( escapes the parenthesis, so it's not seen as part of the regex language, but an actual character you want to match.

Grismar
  • 27,561
  • 4
  • 31
  • 54