1

I'm new to Regular Expressions and I have some questions in my codes.

I tried this but both return false

string pattern = @"\?!";
Console.WriteLine(Regex.IsMatch("!", pattern));
// false
Console.WriteLine(Regex.IsMatch("?", pattern));
// false

But when I did it this way both return true

string pattern = @"\!?";
Console.WriteLine(Regex.IsMatch("!", pattern));
// true
Console.WriteLine(Regex.IsMatch("?", pattern));
// true

So my question is.

  1. Is the order of ? matters?
  2. How does ? work in Regular Expressions?
Lost
  • 43
  • 1
  • 8
  • `?` is different to `\?`. The fair comparison is `!\?` vs `\?!` -- which will return true for the inputs `"!?"` and `"?!"` respectively, and false for everything else. `!?` means "a `!` zero or one times", `!\?` means "a `!` followed by a `?`" – canton7 Mar 18 '20 at 09:39
  • 1
    Unescaped `?` makes the pattern it modifies match *1 or 0 times*, i.e. makes it optional. – Wiktor Stribiżew Mar 18 '20 at 09:41
  • 1
    it seems you're looking for `@"!|\?"` which means a `!` _or_ a `?`. – René Vogt Mar 18 '20 at 09:42
  • @RenéVogt Thank you! That's exactly what I'm looking for. – Lost Mar 18 '20 at 09:47
  • 2
    @WiktorStribiżew Ah, I see why it becomes optional when I put `?` after `!`, thank you for linking the post! – Lost Mar 18 '20 at 09:53

0 Answers0