-1

Let's say we have the following regular expression:

((a(.+?)c ?)+)

This will match:

abc acc aac

What I want to do:

((a(.+?)c ?)(a\3c ?)*)

So that i will only match

abc abc abc

or

acc acc acc

but not item #2 (abc acc aac)

... But without the backreference.

Basically, I want the 3rd capturing group in #1 (.+?) to always match whatever the first match had.

Is this possible?

To make things hairier, this will need to work in JavaScript's regexp engine.

5
  • 2
    You want a regex without backreference? Because it seems backreference is what you need: ((a(.+?)c ?)(a(.+?)c ?)(a\3c ?)*)
    – acdcjunior
    Feb 14, 2014 at 1:27
  • yes, js supports back-references and most other perl regexp features from which it is based...
    – dandavis
    Feb 14, 2014 at 1:39
  • @dandavis Just tested, I did not know this! I always thought that it didn't work in JavaScript. You've now opened up a whole new RegExp world for me (not that I actually use it much over string operations)
    – Paul S.
    Feb 14, 2014 at 1:43
  • I know it's possible in JS's engine to use backreferences, but that's exactly what I'm tying to avoid. It forces you to put redundant sub-expressions in your regex which would be nice to get rid of for readability's sake. Feb 14, 2014 at 2:06
  • RegExp and readable should never be used in the same sentence...
    – dandavis
    Feb 14, 2014 at 2:51

1 Answer 1

0

you can't capture the trailing space if it varies because the memorized value will be literally compared in later refs. moving the variation outside the capturing parens makes it simple:

var rx= /(a(.+?)c) ?\1 ?\1/g ;

// tests/demo
"abc abc abc".match(rx) // ["abc abc abc"]
"abc acc abc".match(rx) // null
"abc acc aac".match(rx) // null
"acc acc acc".match(rx) // ["acc acc acc"]

so, it's a few extra chars of repetition to allow optional spaces, but it works.

3
  • I was hoping to find something without a backreference Feb 14, 2014 at 2:08
  • not sure i understand based on your examples. do you want to hard-code a different RegExp for "abc abc abc" than for "abc acc abc" ? you list a few combinations and to cover them all would take a lot of RegExp objects...
    – dandavis
    Feb 14, 2014 at 2:50
  • The second regexp does exactly what I want, but I want to know if it's possible to do so without a back reference. It should also match "adc adc adc" or "axc axc axc" -- but the middle character (whatever it is) needs to be the same in each repetition. I should also note that this is not the exact regexp I am trying to construct but rather a simplified version of it. Feb 14, 2014 at 3:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.