Link to home
Start Free TrialLog in
Avatar of cplau
cplau

asked on

Replace String in VB.net

Hi all,

For example, I have a string = "ABCDEFGHIJKLMN"
If the string contains this pattern "DEF?" (i.e. DEF follows by any single character). I will substitute it with an empty string.

The value of the string will be "ABCGHIJKLMN" (the four characters DEF? shall be replaced)

How can I do this in VB.NET? Please advise. Thanks.

Avatar of cplau
cplau

ASKER

The value of the string should be "ABCHIJKLMN" (the four characters DEF? shall be replaced)

Dim strText As String = "ABCDEFGHIJKLMN"
Response.Write(strText.Replace("DEF", "@"))

result would be ABC@GHIJKLMN

Avatar of Dirk Haest
you can use regularExpression for that

Dim testString As String = "ABCDEFGHIJKLMN"
Dim str1 As String = System.Text.RegularExpressions.Regex.Replace(testString, "DEF.?", "")
Avatar of cplau

ASKER

My String should be euqal to "ABCHIJKLMN" in the end....
My sarching pattern is "DEF?". It is "DEF" + any single character.
@cplau - try the regular expression example !
Use Regular expression that would only help here i think

1.*, which describes "0 or more occurrences",
2.+, which describes "1 or more occurrences", and
3.?, which describes "0 or 1 occurrence".


abc$ abc, 123abc, any string ending with abc  
Avatar of cplau

ASKER

.? describes "0 or 1 occurrence".

Is there any expression to match extactly 1 occurrence only?
This one may not be ideal but it works


        Dim str As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        Dim str2 = str.Substring(0, str.IndexOf("DEF")) & str.Substring(str.IndexOf("DEF") + 4, str.Length - (str.IndexOf("DEF") + 4))
        MsgBox(str2)
ASKER CERTIFIED SOLUTION
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial