-1

I am trying to find a way of checking if a string starts with only one "X" but not 2 X's in a regular expression.

So I think I have tried

Regex.IsMatch(teststr, "^[^X]{1}?^[XX]");
Regex.IsMatch(teststr, "^[^X]{1}?");
Regex.IsMatch(teststr, "^[^X]{1}");
Regex.IsMatch(teststr, "^[^X]?");

The results should be, if string Starts with 1 X only then give me all except the ones that start with only 1 X. A string with 2 X's is allowed

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Tanya
  • 15
  • 5

1 Answers1

1

What about using a negative lookahead?:

^X(?!X)

Basically the (?!pattern) part denotes a negative lookahead, which will fail your overall expression matching if the pattern in the lookahead fails.

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Which is better, "^X(?!X)" or "^(?=^X(?!X))" – Tanya Apr 24 '19 at 15:59
  • My one matches X when it's not followed by X. The other one Uses a positive lookahead to ensure that the first character is X, and then within that a negative lookahead to ensure that the next character isn't X. I'd say my one is simpler to achieve the same thing. Often with regex there are a few ways to achieve the same thing. i usually opt for the most easy to read option in those cases. – ProgrammingLlama Apr 24 '19 at 16:01