jonathan
jonathan

Reputation: 33

Match and replace first and last character and substring in string using regex VB NET

Sorry for my simple question but I don't know how to do.

I have this string:

Dim SourceString = "{capital?} has a bridge for {people?}"

Now I want ResultString like this:

ResultString = "capital_Den has a bridge for people_Den"

I used

Dim str As String = "{capital?} has a bridge for {people?}"
Dim str1 As String str1 = Regex.Replace(str, "\{?\?\}", "_DEN}")

Result: {capital_DEN} has a bridge for {people_DEN}

But I want this result: capital_DEN has a bridge for people_DEN

Upvotes: 3

Views: 431

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

The \{?\?\} pattern matches an optional {, a ? and then a } char.

You may use

str1 = Regex.Replace(str, "\{(\w+)\?\}", "$1_DEN")

Or, if there can be more than just word chars inside:

str1 = Regex.Replace(str, "\{([^{}]+)\?\}", "$1_DEN")

See the VB.NET demo online and the regex demo. The pattern matches:

  • \{ - a { char
  • (\w+) - Group 1: one or more word chars
  • [^{}]+ - 1+ chars other than { and }
  • \?\} - a ?} substring.

Full VB.NET code snippet:

Dim str As String = "{capital?} has a bridge for {people?}"
Dim str1 As String
str1 = Regex.Replace(str, "\{(\w+)\?\}", "$1_DEN")
Console.WriteLine(str1)
' -> capital_DEN has a bridge for people_DEN

Upvotes: 1

PSK1337
PSK1337

Reputation: 41

First Make a ConsoleApplication

Module Module1

    Sub Main()
        Console.Title = "Combine"
        Dim a As String = "capital_Den"
        Dim b As String = "people_Mar"
        Dim ResultString As String = a & " has a bridge for " & b
        Console.ForegroundColor = ConsoleColor.Green
        Console.WriteLine(ResultString)
        Console.ReadKey()
    End Sub

End Module

Upvotes: 0

Related Questions