views:

329

answers:

3

I'm trying to replace all the carriage return characters in a string obtained from a multi line text box in a Windows Form with the string ", <BR>" so that when I use the string in some HTML it displays correctly.

Function Blah(ByVal strInput As String) As String
  Dim rexCR As Object
  rexCR = CreateObject("VBScript.RegExp")
  rexCR.Pattern = "\r"
  rexCR.Global = True
  Blah = rexCR.Replace(strInput, ",<BR>")
End Function

Tried searching for any of the following characters and still no luck:
\r|\n|\r\c|\cM|\x0d

Problem seems to be the function/expression is not detecting any carriage returns in the text and I have no idea why? I know the function works as I can put a different expression in there as a test and it's OK

Any ideas?

+5  A: 

How about normal strInput.Replace(vbCrLf,",<BR>") without regex?

S.Mark
exactly my point!...
Mitch Wheat
+3  A: 

How about:

Function Blah(ByVal strInput As String) As String
  return strInput.Replace(Environment.NewLine, "<br />")
End Function
ck
+4  A: 

Others have already provided good solutions to your problem. As a general remark, I would like to explain that VB.NET does not have string escape sequences (\n, \r, \t, ...) like C#. String literals in VB.NET are similar to verbatim string literals in C# -- the only character that can be escaped is the double-quote (by doubling it).

Instead, you have to use the VB constants (e.g. vbCrLf, vbTab) or .net constants (e.g. Environment.NewLine) and string concatenation ("Hello World" & vbCrLf instead of `"Hello World\n").

Heinzi
The solutions above using vb constants did not work for me although I can see they would for others.Can you please clarify, is that because when the text in the textbox is assigned to the variable VB.NET leaves out the carriage returns?
9cents
It shouldn't. Can you have a look at the string in the debugger? (Something like `Console.Writeline(strInput)`, then looking at the "Output" tool window in Visual Studio)
Heinzi
I'm such an idiot. I had another piece of code heaps earlier that is cleaning a bunch of characters out and it's wiping the CRs >_<Wouldn't have noticed for ages if it wasn't for your suggestion though! Can I give everyone points? <3
9cents