Reputation: 167
I'm using Netbeans IDE. For a school project I need to read an .ini-file, and get some specific information.
The reason I'm not using ini4j:
Example ini-file:
[Section]
Object1 5 m
number = 12
Object2 6 m
;Comment followed by white line
number = 1\
4
\
means the next command or white lines need to be ignored
So the last part of the ini file actually means: number = 14
My task: I need to store the oject names with the corresponding length (meters) and number into a single string like this: Object1 has length 1m and number 12
My problem:
I use a scanner with delimiter //Z
to store the whole file into a single String.
This works (if I print out the String it gives the example above).
I've tried this code:
String file = file.replaceAll("(\\.)(\\\\)(\\n*)(\\.)","");
If I try to only remove the newlines:
String file = file.replace("\n","");
System.out.println(file);
I get an empty output.
Thanks in advance !
Upvotes: 7
Views: 909
Reputation: 8743
Your problem is that you need to esacpe \
in Java Strings and in regular expressions, so you need to escape them twice. This means if you want to get rid of empty lines you have to write it like this:
file = file.replaceAll("\\n+", "\n");
If you know that a \
at the end of a line is always followed by an empty line then this means that it is actually followed by 2 new line characters which would give the following:
file = file.replaceAll("\\\\\\n\\n", "");
or (it's the same):
file = file.replaceAll("\\\\\\n{2}", "");
\\\\
will result in \\
in the regex, so it matches \
and \\n
will become \n
and match the new line character.
And as mentioned by @Bohemian it would be better to fix the ini-file. Standards make everything easier. If you insist you could use your own file extension, because it is actually another format.
It is also possible to write a regular expression that directly extracts you the values:
file = file.replaceAll("\\\\\\n\\n", "");
Pattern pattern = Pattern.compile("^ *([a-zA-Z0-9_]+) *= *(.+?) *$");
Matcher matcher = pattern.matcher(file);
while (matcher.find()) {
System.out.println(matcher.group(1)); // left side of = (already trimmed)
System.out.println(matcher.group(2)); // right side of = (already trimmed)
}
It's easier than reading lines one by one, but performance could be worse. Anyway usually this is not an issue because ini files tend to be small.
Upvotes: 0
Reputation: 719
You are on right way. But logic is on wrong place. You actually need \n for your logic to recognize new value in your ini file.
I would suggest that you do not read entire file to the string. Why? You will still work with line from file one by one. Now you read whole file to string then split to single strings to analyze. Why not just read file with scanner line by line and analyze these lines as they come?
And when you work with individual line then simply skip empty ones. And it solves your issue.
Upvotes: 2