Regex to get Java import statements -


i writing java program read other java source files , pull out there import statements:

package com.me.myapp  import blah.example.dog.client.fizz; import blah.example.cat.whiskers.client.buzz; import blah.example.shared.foo; import blah.example.server.bar; ...etc. 

i want regex return starting import blah.example. , has client in package name after that. hence regex pick fizz , buzz in example above, not foo or bar.

my best attempt is:

string regex = "import blah.example*client*"; if(somestring.matches(regex))     // 

this regex isn't throwing exception, itsn't working. going wrong it? in advance!

a dot in regex special character means "any character". have escape literal dot, , want dot before * (meaning number of occurrences of character):

"import blah\\.example.*client.*" 

the expression had it:

"import blah.example*client*" 

meant "import blah", followed single wildcard character, followed "exampl", 0 or more e's, "clien", 0 or more t's. match, say, "import blahxexampleeeeeclientttt" or "import blah examplclien".

also, (fixed) regex still match things "import blah.example2.notclient" , "/* import blah.example.client; */", still want enforce location of literal dots around client , start of line, e.g. (unescaped clarity, remember escape slashes in string constants):

^import blah\.example(\.[^.]+)*\.client(\.[^.]+)*; 

where sequence (unescaped clarity):

(\.[^.]+)* 

matches number of individual ".xxx" path components.

note, however, brad mace points out in comments, regular expressions alone still aren't reliable this. don't have way skip, e.g. bunch of import statements commented out /* */ multiline comment.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -