0

Trying to write a stylechecker for some code and using backrefrences in Java for a multiline regex... here's what the regex looks like

.*import com.+([a-zA-Z]+Factory\.class).*\\1.*

Basically, want to find the first instance of a factory class in my code. My example code looks like this:

import com.sample.OtherClass;
import com.sample.cool.SomeFactory.class;

// other nonsense

@Import(clazz = SomeFactory.class)
// other nonsense

My expected match would be the SomeFactory.class in the @Import statement, but it doesn't pick this up... any suggestions?

2
  • 1
    Do nor forget to use Pattern.DOTALL flag when you compile a pattern. Commented Sep 21, 2017 at 16:43
  • 1
    can you add your expected match? Commented Sep 21, 2017 at 16:49

1 Answer 1

1

You can use this regex:

(?s)import\s+com.+?\.([a-zA-Z]+Factory\.class).*(\1)

In Java use:

final String regex = "(?s)import\\s+com.+?\\.([a-zA-Z]+Factory\\.class).*(\\1)";

RegEx Demo

Captured group #1 is SomeFactory.class after import line and captured group #2 is SomeFactory.class after @Import line.

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.