validate file java
I have a flat file like:
A 10
S 20
W A 20 10
S A 45 10
S W S 20 20 20 30
W A S 22 50 20 55
I want to make sure it is well formed, (separated by blank space " ") allowing only a regular expression like:
anyword* then " " then (word*|numbers*)*
where *
is any number of words
- if there is only one word or char there is o开发者_StackOverflow中文版nly one number
- if there are 2 words or chars separated by " " then there must be 2 numbers separated by " "
- if there are 3 words or chars separated by " " then there must be 4 numbers separated by " "
I was doing something like this, but do not know where to incorporate validation of line
try {
input = new BufferedReader(new FileReader(new File(filename)));
String line = null;
while ((line = input.readLine()) != null) {
String[] words = line.split(" ");
if (words.length == 2) {
}
}
}
This regex should do it:
^[a-z]+ (?:\d+|[a-z]+(?: \d+ \d+| [a-z]+(?: \d+){4}))$
I tried to make it as short as possible, but it may be possible to condense it a bit more. This should be used with case sensitivity enabled or you should change all of the [a-z]
to [a-zA-Z]
.
Here is a Rubular.
精彩评论