Stack Exchange
Java Imports declaration regex
I am trying to write a pattern in Java to match against Java import declarations.
Example:
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
// import org.apache.hadoop.mapreduce.Something;
/* import org.apache.hadoop.something.else; */

Would match with only:
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

So far I have the following regex:
"[^A-Za-z0-9\\n]? *import(static|\\s)+[\\w.]*(\\*)?(\\s)*;"

But it's not working. For example:
import org.junit.Test; 
import java.util.ArrayList;
/* The import name; lazily initialized; defaults to a unspecified,...

returns:
import org.junit.Test; 
import java.util.ArrayList; 
import name;

which is wrong.

"it's not working" is the worst possible problem description. What exactly does not work? Do you have false positives? False negatives? Does it crash? Does it burn down your house when you run it?

If you're going to do something like this, are you sure Regex is the answer? Are you sure something lexer/parser oriented (like javac does it) wouldn't be easier?

It's cpaturing more than it should.

I got it working with the use of a flag.
Now it looks like the following:
Pattern.compile("(;|^ *)import(static|\\s)+[\\w.]*(\\*)?(\\s)*;",Pattern.MULTILINE);


This doesn't work if the import declaration uses unicode escapes, e.g. \u0069mport\u0020java\u002Eutil\u002E\u002A\u003B. Perhaps not very likely, but that is valid Java import declaration that the regex will miss. Also you are matching things like importstaticstaticstatic....;

How about this:
^import


Would catch the second line of /* import blah; \nimport foo;*/ when it shouldn't.

@glowcoder ah, ok, with \n. Yes, but noone asked for anything else ;)

It only matches with the first import line.

@Fork nice! how exactly do you run it? Post your matching code

You can try with the examples I posted above. I test the regexes here :http://www.regexplanet.com/simple/index.html before testing in production code.

I am doing this in java, using java.util.regex.Pattern
