[英]VB.NET Regex Replacement
I have a list of fields named flav x (other text) that go 1 through 10. For example, I might have: 我有一个名为flav x (其他文本)的字段列表,范围为1到10。例如,我可能有:
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. 我需要使用VB.NET的Regex
Replace
功能将1
到10
替换为11
到20
,但是我无法正常工作。
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. 我将使用2个正则表达式运行来获得所需的结果,因为不可能使用带有替代项的替换文字。
The first regex would replace 10
to 20
and the second will handle 1 to 9 digits: 第一个正则表达式将替换
10
到20
,第二个将处理1到9位数字:
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
) 参见IDEONE演示 (输出为
flav12PG20Pct101
)
Regex explanation : 正则表达式说明 :
(?<=\\D|^)
- A positive look-behind that makes sure there is no digit ( \\D
) or start of string ( ^
) before... (?<=\\D|^)
-一个正向后方查找,确保没有数字( \\D
)或字符串的开头( ^
)... [1-9]
- a single digit from 1
to 9
(or, in the second regex, 10
matching literal 10
) [1-9]
-从1
到9
一位数字(或在第二个正则表达式中,为10
与原义10
匹配的数字) (?=\\D|$)
- A positive look-ahead that makes sure there is no digit ( \\D
) or the end of string ( $
) after the digit. (?=\\D|$)
-一个正向提前查询,可确保没有数字( \\D
)或数字后的字符串结尾( $
)。 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]*|^)
. 如果必须检查字符串中是否存在
flav
则可以使用稍微不同的后视: (?<=flav\\D*|^)
,或者-如果在flav
和数字之间不应出现空格: (?<=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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.