Link to home
Create AccountLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

ASP.NET / VB / REGEX: Strip Redundant Whitespace

The following PHP code does exactly what I need:
$buffer = preg_replace("/(?=\s\s)\s*?(\n)\s*|(\s)\s+/", "$1$2", trim($buffer));

Open in new window


How can it be converted into ASP.NET/VB code?
SOLUTION
Avatar of Derek Jensen
Derek Jensen
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of hankknight

ASKER

bigdogdman, your code removes all whitespace.  I want it to remove only redundant whitespace.

CodeCruiser, I do not know how to implement your idea.

This does not work:

<%@ Page Language="VB" AutoEventWireup="false" %>
<%

 Dim outputData as String = "hello           world    " & vbCrLf & vbCrLf & vbCrLf &  "        123"
 outputData = System.Text.RegularExpressions.RegEx.Replace(outputData, "/(?=\s\s)\s*?(\n)\s*|(\s)\s+/", "$1$2")
 Response.write(outputData)

%>

Open in new window

Simpler approach

While str.Contains("  ")
   str = str.Replace("  ", " ")
End While
My REGEX does more than just more than replace spaces.  If there are one or more line breaks it keeps one line break and removes the extra line breaks.  It also treats tabs and spaces the same.  I want my PHP REGEX code to be converted to work with ASP.NET / VB.
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Thanks.

Here is the working code, based on kaufmed's translation:
<%@ Page Language="VB" AutoEventWireup="false" %>
<%
 Dim outputData as String = "hello       " & vbCrLf &  " zzzz             world    " & vbCrLf &  vbCrLf &  vbCrLf & vbCrLf & vbCrLf &  "              123"
 outputData = System.Text.RegularExpressions.Regex.Replace(outputData.Trim(), "(?=\s\s)\s*?(\n)\s*|(\s)\s+", "$1$2")
 Response.write(outputData)
%>

Open in new window

Ooops! Forgot that the pattern and target are flip-flopped between languages. Good catch  = )