I have an application that downloads a .txt
file via FTP, and then it calls some sql to insert the file data into my database. I want to check whether the file is in the correct format before trying to insert.
The file should consist of some number of rows, each with the following format:
(4 letter code) (tab) (3 or 4 letter code) (tab) (date as dd-MMM-yy) (tab) (variable length text description) (tab) (1 letter code)
Is there a good way to check whether every line in the file 开发者_JS百科follows this pattern, and warn me if it doesn't?
Sounds like a typical use case for regular expressions. Create a regex pattern and match it against each line in your file.
If you aren't familiar with regex, maybe you'll find this link also helpfull in addition to the links above.
The pattern you are looking for is propably this:
^\w{4}\t\w{3,4}\t\d{2}\-\D{3}\-\d{2}\t.*\t\w$
it will match text like these (imagine _ is a tab):
test_foo_12-FEB-11_this is a text_X
test_fbar_01-jan-15_bla bka bla_o
but not:
test123_foo_12-FEB-11_this is a text
You could do something like this:
Dim pattern = "^\w{4}\t\w{3,4}\t\d{2}\-\D{3}\-\d{2}\t.*\t\w$"
For Each line In text
Console.WriteLine(String.Format("{0} {1}", _
line, _
If(Regex.IsMatch(line, pattern), "is valid", "is invalid"))
Next
精彩评论