• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 379
  • Last Modified:

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.

0
cplau
Asked:
cplau
  • 3
  • 2
  • 2
  • +2
1 Solution
 
cplauAuthor Commented:
The value of the string should be "ABCHIJKLMN" (the four characters DEF? shall be replaced)

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

result would be ABC@GHIJKLMN

0
 
DhaestCommented:
you can use regularExpression for that

Dim testString As String = "ABCDEFGHIJKLMN"
Dim str1 As String = System.Text.RegularExpressions.Regex.Replace(testString, "DEF.?", "")
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
cplauAuthor Commented:
My String should be euqal to "ABCHIJKLMN" in the end....
My sarching pattern is "DEF?". It is "DEF" + any single character.
0
 
DhaestCommented:
@cplau - try the regular expression example !
0
 
kambleamarCommented:
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  
0
 
cplauAuthor Commented:
.? describes "0 or 1 occurrence".

Is there any expression to match extactly 1 occurrence only?
0
 
CodeCruiserCommented:
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)
0
 
wdosanjosCommented:
@cplay, the pattern is just "DEF." without the ?.

@Dhaest code with the correct pattern:
Dim testString As String = "ABCDEFGHIJKLMN"
Dim str1 As String = System.Text.RegularExpressions.Regex.Replace(testString, "DEF.", "")

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now