0

I'm trying to perform a simple regex find and replace, adding a tab into the string after some digits as outlined below.

From

a/users/12345/badges

To

a/users/12345   /badges

I'm using the following:

s = regex.replace(s, "(a\/users\/\d*)("a\/users\/\d*\t)", $1 $2")

But im clearly doing something wrong.

Where am I going wrong, I know its a stupid mistake but help would be gratefully received.

VBVirg

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
vbvirg20
  • 115
  • 12

2 Answers2

1

You can achieve that with a mere look-ahead that will find the position right before the last /:

Dim s As String = Regex.Replace("a/users/12345/badges", "(?=/[^/]*$)", vbTab)

Output:

a/users/12345   /badges

See IDEONE demo

Or, you can just use LastIndexOf owith Insert:

Dim str2 As String
Dim str As String = "a/users/12345/badges"
Dim idx = str.LastIndexOf("/")
If idx > 0 Then
   str2 = str.Insert(idx, vbTab)
End If
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

When I read, "adding a tab into the string after some digits" I think there could be more than one set of digits that can appear between forward slashes. This pattern:

"/(\d+)/"

Will capture only digits that are between forward slashes and will allow you to insert a tab like so:

Imports System.Text.RegularExpressions

Module Module1
    Sub Main()
        Dim str As String = "a/54321/us123ers/12345/badges"
        str = Regex.Replace(str, "/(\d+)/", String.Format("/$1{0}/", vbTab))

        Console.WriteLine(str)
        Console.ReadLine()
    End Sub
End Module

Results (NOTE: The tab spaces can vary in length):

a/54321 /us123ers/12345 /badges

When String is "a/54321/users/12345/badges" results are:

a/54321 /users/12345    /badges
Shar1er80
  • 9,001
  • 2
  • 20
  • 29