-2

Edit------ Found the answer, will post for future reference soon.

I was wondering if I could get help with a simple regex task.

I have three letters: X, Y and Z (those exact letters).

I need to write a regex for a word composed only of those three that does not have the same letters twice immediately after each other.

So for example:

Xyxzyx qualifies, but Xxyzx does not, because of the Xx.

Edit: oh god i forgot to mention this. I have tried looking at the thing multiple times, have come up with something like this so far:

when there are only two letters, the only possible arrange ment is like this: y? (xy)* x?. Then, the third letter may break the pattern sometimes (or never), and i am trying to look into what happens after and how it can loop back to the repeating two characters, i think it will look something like this:

y? ( (xy)* x? z (-some stuff-) )* -possibly more stuff-

Also i am not permitted to use programming language-specific stuff, like reversal, only pure regex.

user58779
  • 1
  • 2

1 Answers1

-1

The simpliest solution I can think of is

^(?:x(?=y|z|$)|y(?=x|z|$)|z(?=x|y|$))+$

I think you cannot solve it without a lookup (?=..). "pure regex" is not defined ;)

(x(?=[yz]|$) means match x and test if the next character is yor z or the end of line/string $.


A possible solution without a lookup is to match every combination. I'll show it for 2 characters only.

^(?:x(?:yx)*y?|y(?:xy)*x?)$

x(yx)*y?matches an x, any amount of the 2 character sequence xy and a pending y, if there is one..

As state diagram:

(1) --x--> (2)
(1) --y--> (3)
(2) --y--> (3)
(3) --x--> (2)
(2) --$--> (4)
(3) --$--> (4)

where (1) is the start state and (4) the end state. $ means end of string

Wolfgang Kluge
  • 895
  • 8
  • 13
  • I read the assignment as disallowing lookaheads. – tripleee Dec 06 '15 at 20:13
  • @tripleee: I'm afraid you're right – Wolfgang Kluge Dec 06 '15 at 20:29
  • Well, thank you for your attempt at helping me, i found a solution. I have other things to do right now, but will soon post it here for future reference for anybody who may need it someday. Also will change post title to something that might turn up in a SE search on this problem. – user58779 Dec 06 '15 at 20:54