tags:

views:

357

answers:

2

Hi,

I have text like this format

"term: 156^^^:^^59 datainput" Or "term: 156^^^:59 datainput" or "term: 156:^^^59"

The "^" represented white space. Notice the white space between the the two numbers and the colon. There 2, 3, 4 or even 7 white space between the two number. I want to remove these white space so that the text can be in this format :

"term: 156:59 datainput"

which is no more space between the the two number -> 156:56. I want to remove the white space between the number and the colon only.

Thanks for any input.

+5  A: 

Try the following

Dim result = Regex.Replace(input, "(\d)\s*:\s*(\d)", "$1:$2")

This uses a regular expression to match the spaces in between the numbers and the colons. Any pattern such as this will be replaced with the last argument. The $1 and $2 are escape sequences which say "replace with text matched by the first and second parenthesis". In this case it will be a single digit.

JaredPar
You got it right. Regular expression is powerful.
Rithet
Regular expressions rock. +1
Jose Basilio
@Jose, they rock until you have to maintain a 4 line regex the guy before you wrote ;)
JaredPar
Often a developer has a problem and thinks "I know, I'll use regular expressions", now he has two problems...
BenAlabaster
@balabaster, absolutely true. Unforutanately most people don't realize the inherit limitations of regex's and as a result attempt to use them for problems they cannot possibly solve. Results in a lot of wasted time. QA loves this though because it inevitable leads to a bug farm :)
JaredPar
+1  A: 

I think regex will help handle the different number of whitespace characaters.

 Dim text As String = "term: 156      :     59 datainput "
 text = Regex.Replace(text, "([0-9])\s*:\s*([0-9])", "$1:$2", RegexOptions.Singleline)
Joshua Belden
15 secs late :D
Rithet
Different regex. Same result. +1
Jose Basilio