I have a list of fields named flav x (other text) that go 1 through 10. For example, I might have:
flav2PGPct
I need to turn it to
flav12PGPct
I need to replaced 1
through 10
with 11
through 20
using VB.NET's Replace
function with Regex, but I can't get it working right.
Can anyone help?
Here's what I've tried:
(\.)flav*[1-9]
I have no idea what to place in the replacement box...
使用此正则表达式进行搜索: (flav)(\\d\\w*)
并使用该正则表达式进行替换: ${1}1$2
。
I'd use 2 regex runs to obtain the desired result because it is not possible to use a replacement literal with alternatives.
The first regex would replace 10
to 20
and the second will handle 1 to 9 digits:
Dim rx1to9 As Regex = New Regex("(?<=\D|^)[1-9](?=\D|$)") '1 - 9
Dim rx10 As Regex = New Regex("(?<=\D|^)10(?=\D|$)") '10
Dim str As String = "flav2PG10Pct101"
Dim result = rx10.Replace(str, "20")
result = rx1to9.Replace(result, "1$&")
Console.WriteLine(result)
See IDEONE demo (output is flav12PG20Pct101
)
Regex explanation :
(?<=\\D|^)
- A positive look-behind that makes sure there is no digit ( \\D
) or start of string ( ^
) before... [1-9]
- a single digit from 1
to 9
(or, in the second regex, 10
matching literal 10
) (?=\\D|$)
- A positive look-ahead that makes sure there is no digit ( \\D
) or the end of string ( $
) after the digit. If you must check if flav
is present in the string, you may use a bit different look-behind: (?<=flav\\D*|^)
, or - if spaces should not occur between flav
and the digit: (?<=flav[^\\d\\s]*|^)
.
Regexes work best with strings rather than numbers, so an easy way is to use a regex to get the parts of the string you want to adjust and then concatenate the calculated part in a string:
Option Strict On
Option Infer On
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim re As New Regex("^flav([0-9]+)(.*)$")
Dim s = "flav1PGPct"
Dim t = ""
Dim m = re.Match(s)
If m.Success Then
t = CStr(Integer.Parse(m.Groups(1).Value) + 10)
t = "flav" & t & m.Groups(2).Value
End If
Console.WriteLine(t)
Console.ReadLine()
End Sub
End Module
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.