Reputation: 225
I have a string variable.
Dim str As String = "ABBCD"
I want to replace only the second 'B' character of str (I mean the second occurrence)
my code
Dim regex As New Regex("B")
Dim result As String = regex.Replace(str, "x", 2)
'result: AxxCD
'but I want: ABxCD
What's the easiest way to do this with Regular Expressions.
thanks
Upvotes: 2
Views: 331
Reputation: 1943
Dim str As String = "ABBCD"
Dim matches As MatchCollection = Regex.Matches(str, "B")
If matches.Count >= 2 Then
str = str.Remove(matches(1).Index, matches(1).Length)
str = str.Insert(matches(1).Index, "x")
End If
First we declare the string 'str', then find the matches of "B". If we found two results or more, replace the second result with "x".
Upvotes: 1
Reputation: 1
'Alternative way to replace the second occurrence
'only of B in the string with X
Dim str As String = "ABBCD"
Dim pattern As String = "B"
Dim reg As Regex = New Regex(pattern)
Dim replacement As String = "X"
'find position of second B
Dim secondBpos As Integer = Regex.Matches(str, pattern)(1).Index
'replace that B with X
Dim result As String = reg.Replace(str, replacement, 1, secondBpos)
MessageBox.Show(result)
Upvotes: 0
Reputation: 98901
I assume BB
was just an example, it can be CC
, DD
, EE
, etc..
Based on that, the regex below will replace any repeated character in the string.
resultString = Regex.Replace(subjectString, @"(\w)\1", "$1x");
Upvotes: 1
Reputation: 12797
If ABCABCABC
should produce ABCAxCABC
, then the following regex will work:
(?<=^[^B]*B[^B]*)B
Usage:
Dim result As String = Regex.Replace(str, "(?<=^[^B]*B[^B]*)B", "x")
Upvotes: 1
Reputation: 60174
How about:
resultString = Regex.Replace(subjectString, @"(B)\1", "$+x");
Upvotes: 1