We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Replace String in VB.net

cplau
cplau asked
on
Medium Priority
412 Views
Last Modified: 2012-08-13
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.

Comment
Watch Question

Author

Commented:
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

Dirk HaestProject manager
CERTIFIED EXPERT

Commented:
you can use regularExpression for that

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

Author

Commented:
My String should be euqal to "ABCHIJKLMN" in the end....
My sarching pattern is "DEF?". It is "DEF" + any single character.
Dirk HaestProject manager
CERTIFIED EXPERT

Commented:
@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  

Author

Commented:
.? describes "0 or 1 occurrence".

Is there any expression to match extactly 1 occurrence only?
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
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)
Top Expert 2011
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.