-1

I'm trying to exclude strings where the first char is equal to the third char:

passing strings: X9K3 V3Z5

not passing strings: A4A9 R5R1

I tried ^(.).[^\1].$

but I'm too new to regex to understand why it failed.

ohadgk
  • 2,297
  • 2
  • 9
  • 10
  • 1
    You could reverse your logic. I.E., use `^(.).\1` and accept strings that do _not_ match that pattern (and they have at least 3 characters, if that's a requirement). This is particularly useful if you're using a regex engine that doesn't support Lookarounds. Otherwise, check anubhava's answer below. – ICloneable Oct 01 '20 at 19:16

1 Answers1

2

You may use this regex:

^(.).(?!\1).+$

RegEx Demo

  • [^\1] does not do what it intends to because inside [...] every character becomes literal after first ^ so it just matches everything except \ and 1.
  • (?!\1) on the other hand is a negative lookahead which fails the match if character on next position is not same as what we captured in group #1.
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • Thanks! any reason why your suggested expression: ^(.).(?!\1).+$ works, but this one: ^(.)9(?!\1)5+$ dose not? – ohadgk Oct 01 '20 at 19:33
  • 2
    @ohadgk your regex `^(.)9(?!\1)5+$` first checks that the character after nine is not the same as the first character, then says it must be one or more fives. So if you're trying to match "a95555", it'll do that. Maybe you meant `^(.)9(?!\1).5.+$`? – Gary Oct 01 '20 at 19:37