我有一个字符串变量。
Dim str As String = "ABBCD"
我想替换仅限第二个' B' str的字符(我的意思是第二次出现)
我的代码
Dim regex As New Regex("B")
Dim result As String = regex.Replace(str, "x", 2)
'result: AxxCD
'but I want: ABxCD
使用正则表达式执行此操作的最简单方法是什么。
感谢
答案 0 :(得分:0)
怎么样:
resultString = Regex.Replace(subjectString, @"(B)\1", "$+x");
答案 1 :(得分:0)
答案 2 :(得分:0)
如果ABCABCABC
应生成ABCAxCABC
,那么以下正则表达式将起作用:
(?<=^[^B]*B[^B]*)B
用法:
Dim result As String = Regex.Replace(str, "(?<=^[^B]*B[^B]*)B", "x")
答案 3 :(得分:0)
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
答案 4 :(得分:0)
我认为BB
只是一个示例,可以是CC
,DD
,EE
等。
基于此,下面的正则表达式将替换字符串中的任何重复字符。
resultString = Regex.Replace(subjectString, @"(\w)\1", "$1x");
答案 5 :(得分:0)
'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)