1

I am currently refactoring my codebase to replace code like this:

one && one.two && one.two.three

with the equivalent using optional chaining:

one?.two?.three

but I'm having trouble coming up with a regular expression that matches instances of the former.


So far I've come up with this:

(([a-zA-Z0-9]*\.)*[a-zA-Z0-9]* && )+

which is OK but has a lot of false-positives (matching things like a && a.c && a.d.e && a.f.g.h)


The regex should match expressions of the form (any length):

  • one && one.two && one.two.three...
  • one.two && one.two.three && one.two.three.four...

But not match:

  • one && two...
  • one && two.three...

Any help is very much appreciated!

4
  • 1
    Maybe something along (\w+(?:\.\w+)*)\s*&&\s*(\1\.\w+)\s*&&\s*\2\.\w+ which will match condition chains with 3 elements. This will consequently also find larger chains but only match the first 3 elements. If you plan to replace them by hand, that should work anyways. Commented Jun 21, 2018 at 19:15
  • @SebastianProske excellent! If you convert to answer I'll gladly accept Commented Jun 21, 2018 at 19:27
  • 1
    How about (\b(\w[\w.]*)(?=( +&& +)\2|$)( +&& +)?){2,}? Commented Jun 21, 2018 at 19:57
  • @revo that also works great :) thanks Commented Jun 21, 2018 at 20:09

1 Answer 1

2

Seems you can make use of backreferences here and use

(\b\w+(?:\.\w+)*)\s*&&\s*(\1\.\w+)\s*&&\s*\2\.\w+

to match sequences of 3 elements as shown in your samples, where the first element is a sequence of dot separated words, the second is the first element + dot + another word and the third is the second element + dot + another word.

This will only match the first 3 elements if you have chains of 4 or more, but if you plan to do the replacements by hand, this shouldn't be a blocker.

See it in action here

Sign up to request clarification or add additional context in comments.

Comments

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.