Search "if condition" in .java file - java

I want to search all if conditions in .java file.
I am using BufferedReader to read file and pattern to search condition.
My program searching all if but when my file look this:
// if{}
I get bad result.
I want to get only valid if conditions (also if{} and if {} - between if and { is space), without conditions in comments.
How should it look regex?
Full code: http://pastebin.com/55RMfwg2

^(?!a\\/\\/) *if *\\{(.|\n)*}
This regex will look for if without // before it and with optional space after it,
it will also catch the closing bracket } and allow new line character between the brackets.
Moreover it will accept spaces before the if.
If multi-line comments /* */ should be skipped also, I think as other people wrote, it will be easier to just clean the file before.
There are many websites that can help you to find the exact regex, i will recommend RegExr.

Related

How do I ignore specific character when it's inside a comments or quote using regex?

I am writing a program which can trace depth of curly braces in a code file line by line, the idea is to have a global variable incremented every-time i find {and decremented every time i find }, this is easy and I already have it done, Now I want to to make sure that I don't count the braces that are inside quotes (i.e. string) or when it's in a comment (// or /* */), I am thinking to utilize the power of regex in this problem, but I am not sure what such regex should look like, I was thinking something like "{ //^"/ "/" " but this is not correct, Any ideas?
You could also try to remove the comments and strings from the lines like this:
lineString.replaceAll("\".*?\"", "") // strings
.replaceAll("/\\*.*?\\*/", "") // block comment
.replaceAll("//.*", ""); // line comment
Afterwards, there should be not comments and strings left. You might be able to put all this in one regex by concatenating it with |.
Edit: I do not know whether block comments in your input span multiple lines. My proposal does not cover that case. As you process the file line by line, you would have to look for /*, set a flag, and ignore everything until you find a */.

Removing comments from code character by character [Java]

I need to remove comments from code, but in this case I'll have to do it without using
System.out.println(sourceCode.replaceAll("//.*|/\\*((.|\\n)(?!=*/))+\\*/", ""));
The program needs to check the code character by character to look for "/" and then proceed to check if the next character is "/" or "*".
I'm looking for a good way to read through the code and check characters letter by letter
This is a classic problem given to new learners in Java. I would suggest to go for a simple approach as it is intended to help you practice your coding skills
Read the java source code as a file in your program char by char.
Search for comments beginning. In this case, there are 2, /* and //.
Open a string buffer and start writing the read contents into it.
If its /*, then don't write it in buffer. Keep on moving to next character till you find */.
Repeat till end of file is reached.
If single line comments need to be removed, then same algorithm can be followed till you get a new line character.
If you need help in reading from file char by char, refer to Java documentation.
When end of file is reached, then write the string buffer back to the file.

vimrc brackets/parenthesis java,c indentation new line

If the code we have looks like
for(...){
}
after reformatting I'd like it to look like
for(...)
{
}
as well for all functions, methods, classes etc.
I found something similar in other article in stackoverflow but it was a regular expression and needed to type every time in the vim console. And I am looking for something to put in the vimrc file (if possible) and to work every time I open it.
Well this is the one I've found:
:%s/^(\s*).*\zs{\s*$/\r\1{/
in http://stackoverflow.com/questions/4463211/is-there-a-way-to-reformat-braces-automatically-with-vim but the thing is it adds a new line even if the bracket is on the right place... and still don't know how to map it to key combination.
(edited with a more accurate pattern)
This should do the trick:
nnoremap <F9> :%s/^\(\s*\).\+\zs{\ze\s*$/\r\1{<cr>
But it it doesn't really sound "safe" to me.
Instead, you could do:
nnoremap <F9> :%s/^\(\s*\).\+\zs{\ze\s*$/\r\1{/c<cr>
which will ask for a confirmation for each match.
Or record a macro and play it back using :global.
edit
Your pattern, :%s/^(\s*).*\zs{\s*$/\r\1{/, is wrong because:
the capture parentheses are not properly escaped, (\s*) instead of \(\s*\)
.* would match any number of any character, including 0 which is why the substitution also works on lines with a single {.

Detect when file can't be created because of bad characters in name

Can anyone tell me how to cope with illegal file names in java? When I run the following on Windows:
File badname = new File("C:\\Temp\\a:b");
System.out.println(badname.getAbsolutePath()+" length="+badname.length());
FileWriter w = new FileWriter(badname);
w.write("hello world");
w.close();
System.out.println(badname.getAbsolutePath()+" length="+badname.length());
The output shows that the file has been created and has the expected length, but in C:\Temp all I can see is a file called "a" with 0 length. Where is java putting the file?
What I'm looking for is a reliable way to throw an error when the file can't be created. I can't use exists() or length() - what other options are there?
In that particular example, the data is being written to a named stream. You can see the data you've written from the command line as follows:
more < .\a:b
For information about valid file names, look here.
To answer your specific question: exists() should be sufficient. Even in this case, after all, the data is being written to the designated location - it just wasn't where you expected it to be! If you think this case will cause problems for your users, check for the presence of a colon in the file name.
I would suggest looking at Regular Expressions. They allow you to break apart a string and see if certain characteristics apply. The other method that would work is splitting the String into a char[], and then processing each point to see what's in it, and if it's legal... but I think RegEx would work much better.
You should take a look at Regular Expressions and create a pattern which will match any illegal character, something like this:
String fileName = "...";
Pattern pattern = Pattern.compile("[:;!?]");
Matcher matcher = pattern.match(fileName);
if (matcher.find())
{
//Do something when the file name has an illegal character.
}
Note: I have not tested this code, but it should be enough to get you on the right track. The above code will match any string which contains a :, ;, `!' and '?'. Feel free to add/remove as you see fit.
You can use File.renameTo(File dest);.
Get the file name first:
String fileName = fullPath.substring(fullPath.lastIndexOf('\\'), fullPath.length);
Create an array of all special chars not allowed in file names.
for each char in array, check if fileName contains it. I guess, Java has a pre-built API for it.
Check this.
Note: This solution assumes that parent directory exists

How to remove particular string from .asp file, using Java?

I'm currently writing something which is validating our vbscript files. Right at the start I wish to remove all lines of code which are comments. I was expecting to be able to use the "'" (comment symbol in vbscript) and '\n'. However, when I write the content of the file to screen, the new lines are not formatting. Does this mean there are actually no new lines in the original vbscript file and if not, how could I remove comments?
first read whole file in string example
then use regex or simply substring for removing extra syntax
How are you parsing the file? Are you also taking the '\r' into consideration when removing the comments? Or maybe you are accidentally removing all newline characters.
I would create some state flags to tell the parser when I was in a comment or not.

Categories