0

I'd like to create a regex pattern that matches alphanumeric strings with an optional prefix of "1-1". Valid matches include:

  • 1-1abc123
  • TestString
  • 12345

And invalid matches include:

  • 1-2abc123
  • 1--1abc123
  • --something

So far, I've tried the following pattern in C#, but it matches the first two examples of invalid patterns:

const string PATTERN = @"(1-1)?[a-zA-Z0-9]+";

**EDIT: ** This was marked as an exact duplicate of another post, but it's completely different. **EDIT 2: ** Never mind -- this is indeed a duplicate. It would have been nice to get clarification for why it's a duplicate when marking it, but here we are.

Alex
  • 139
  • 9
  • This is not a duplicate of the linked SO post. – Alex Jan 08 '18 at 15:21
  • 2
    use ^(1-1)?[a-zA-Z0-9]+$ to indicate start and end of string – Hans Kilian Jan 08 '18 at 15:23
  • 2
    Yes it is a duplicate :) In your case, only the "2abc123" and "1abc123" are matched in invalid examples. The problem is that you want the regex to match the entire string really ^^ So, using ^ at first and $ in the end to specify the start and end of your string. – Julien B. Jan 08 '18 at 15:25
  • Thanks, Hans. I tried that, but the regex pattern is still matching patterns like `1-2abc123` and `1--1abc123`. These should not be valid patterns. – Alex Jan 08 '18 at 15:26
  • 1
    You can try [regexr](https://regexr.com/) to understand what is getting matched by the regular expression, and why :) – Julien B. Jan 08 '18 at 15:27
  • 2
    I had left out the final $ character. My mistake. Thanks everyone for your help! – Alex Jan 08 '18 at 15:28
  • `((1\-1)[a-zA-Z0-9]+)|[a-zA-Z]+[a-zA-Z0-9]+` Try this. It should do the work. – Mukesh Jan 09 '18 at 05:31
  • 1
    @Mukesh No it doesn't. For exactly the same reason that Alex's regex doesn't work. This is seen in Hans' solution and is explained by Julien. On top of which you are unnecessarily escaping the `-`, unnecessarily using capturing groups, and failing to capture single alphabetic character strings. Your non-working regex should read `1-1[a-zA-Z0-9]+|[a-zA-Z]+[a-zA-Z0-9]*`. Your actually working regex would be `^(?:1-1[a-zA-Z0-9]+|[a-zA-Z]+[a-zA-Z0-9]*)$`. This is more complicated than Hans' solution and *still* excludes the case where a non-prefixed alphanumeric string starts with a numeral! – robinCTS Jan 09 '18 at 08:05

0 Answers0