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

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

You can probably ditch the regex and just do a string replace "/badges" to vbTab & "/badges"
Unless there is anything else. I have also added another non-regex solution now. @vbvirg20, is that what you are looking for?
Or is Dim s As String = "a/users/12345/badges".Replace("/badges", vbTab + "/badges") enough (meaning /badges is always a known substring)?
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.