1

I have a regex pattern like this

(\w)(..\1..\1|...\1...\1|....\1....\1|.....\1.....1)

I want to make it shorter. As we can see the number of dots is from 2 to 5. I want to write something like (\w)(.{2,5}\1){2} but in this case it will match some wrong strings q00q000q. Also I can try to use number reference but it repeats chars from a string instead of symbols .. Is it possible to repeat pattern .{2,5} as a specific count of .?

UPDATE It was a challange about tic-tac-toe game. I needed to write down a regexp of length <=50 which can be used to find out if somebody wins

9
  • In other words I need a reg exp for string like that QaaaQaaaQaaaQ (count of letter 'a' doesn't specified) Commented Jan 7, 2016 at 22:13
  • I think you need to escape the '.'. As in \.. Commented Jan 7, 2016 at 22:14
  • 1
    @Leo I don't think it's feasible. Not with a simple regex at least. You would need to "count" the dots and keep state. I don't know of any feature within python regex that can do this. Commented Jan 7, 2016 at 22:18
  • 1
    If I may ask, why do you want to make it shorter? Knowing that might help us to suggest alternatives. Commented Jan 7, 2016 at 22:33
  • 1
    not possible. what you want is a classical example of non-regular language. see en.wikipedia.org/wiki/Regular_language. it describes that regular expression is not capable of remembering how many characters it counted Commented Jan 7, 2016 at 22:49

1 Answer 1

1

You could generate the regex with a Python expression:

In [13]: r'(\w)(%s)'%'|'.join(r'{dots}\1{dots}\1'.format(dots='.'*i) for i in range(2,6))
Out[13]: '(\\w)(..\\1..\\1|...\\1...\\1|....\\1....\\1|.....\\1.....\\1)'
Sign up to request clarification or add additional context in comments.

2 Comments

Cool but we're back to square one :)
Maybe, maybe not. If OP's problem is "my regex is 16K characters long and I don't want to type it by hand", then my solution helps. If OP's problem is "I want to discover a cool new feature of regex", then I didn't help him at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.