1

Is there a single regular expression that will match strings that have the letter "a" or "x" at certain indexes?

For example, the indexes may be

0, 3, 6
1, 4, 7
2, 5, 8

Possible patterns according to these indexes:

"a--a--a--"
"-x--x--x-"
"--a--a--a"

Other occurrences of "a" or "x" are okay. I just want to make sure certain indexes contain "a".

EDIT: This problem is a subproblem of a tic-tac-toe board. I'm to determine if there is a winner by using a regular expression. I don't want the answer to this. I just want a bit of a push to help me move toward the final answer. The above is to help me find a regex that would identify if there is a vertical winner.

anubhava
  • 761,203
  • 64
  • 569
  • 643
brienna
  • 1,415
  • 1
  • 18
  • 45

3 Answers3

3

If your tic-tac-toe looks like a 9 chars long string, testing this pattern should suffice to know if there's a vertical line:

a..a..a
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
2

You can use this regex:

([a-zA-Z])..\1..\1

RegEx Demo

  • ([a-zA-Z]) will match and capture any letter in group #`
  • Then another 2 instances of same letter at n+3 and n+6 positions are matched using back-reference \1, where n is the first position of letter.
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • He said `a` is allowed at other positions, it could be before the first one at the index he cares about. So you shouldn't have `[^a]*` to exclude those. – Barmar Dec 15 '16 at 20:13
  • 1
    I chose this answer because of its flexibility, cuz now I can test for any character(s). Thanks! – brienna Dec 15 '16 at 22:35
1

Since a appears every 3 characters, (a..)* will match those repetitions. Then you just need to precede that with a pattern that matches the required number of characters before it, which is simply n-1 . patterns.

So for the three examples you gave, it's

^(a..)*
^.(a..)*
^..(a..)*
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Knowing he always matches this on a 9-char string, why not simply `(a..){3}` ? – JM Lord Dec 15 '16 at 20:17
  • I thought he wanted to find the match starting at a specific position. – Barmar Dec 15 '16 at 20:18
  • You're right, the regex I gave works only for the problem he gave (verticals), but would not work for the diagonals of the tic-tac-toe. Anyways, this matters not : @Casimir et Hippolyte 's answer is right on, and extremely simple. – JM Lord Dec 15 '16 at 20:21