Question

I am parsing a text file and importing it into a Data Grid View. The file is set up like so:

number 1 .......... 845.6
number 2 .......     0.0001
col 1       col 2      col 3
1.233       4.55       1000

I need to get these values into a DGV then I can insert them into a Excel Template. I have everything working except for one line. the "number 1" line ends up all in one cell. I'll explain why.

I use the following code to process each line and sort of create a csv out of the data first.

TextLine = Regex.Replace(TextLine, " {2,}", "  ")
TextLine = Replace(TextLine, "  ", ",")

Since the data in the file is separated by more then one consecutive space on every line (except "number 1") I can just replace each occurrence with a comma and I get a nice result. What I was trying to do was replace consecutive periods with a space so "number 1" is separated from the value.

I have tried a few things:

TextLine = Regex.Replace(TextLine, "(.)\1{2,}", "  ")
TextLine = Regex.Replace(TextLine, ".{2,}", "  ")

the top one works, but also obviously gets rid of other characters that are consecutive. I also can't just remove periods, as some numbers have a decimal. I was thinking the solution might be using "Chr(46)" in that function, but I can't seem to make it work.

Was it helpful?

Solution

You need to escape the dot with a backslash so that it doesn't have a special meaning.

It looks like this is what you want:

Dim textLine As String = "number 1 .......... 845.6"
textLine = Regex.Replace(textLine, "\.{2,}", ",")
Console.WriteLine(textLine) ' outputs "number 1 , 845.6"

Or maybe Regex.Replace(textLine, "\.{2,}", " ") to replace two-or-more consecutive dots with a space.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top