gpt4 book ai didi

选择第一个出现的数字的正则表达式,在循环中

转载 作者:行者123 更新时间:2023-12-04 08:09:16 25 4
gpt4 key购买 nike

所以基本上我有这些类型的字符串
Unique
Decimal string
Hundred
我想替换出现的第一个数字,不幸的是它们有时会出现数百个小数或唯一数字。这是我尝试使用的代码和模式。

Sub Validator()
Dim r As Range
Dim s As String
Dim news As String
Dim regex As New RegExp
Dim regex2 As New RegExp
regex.Global = True
regex.Pattern = ",[\s\S]*$"
regex2.Pattern = "(^|\\s)([0-9]+)($|\\s)"


Sheet1.Activate


For Each r In Range("B1:B17")
s = r.Value

news = regex2.Replace(s, " ")

r.Value = news

Next r

End Sub
请忽略模式 1,他基本上在逗号之后取出了所有内容,并且成功的问题是模式 2,当我执行我的代码时它基本上什么都不做,我知道代码是有效的,因为第一个正确出现。
A3 Sport 1.8 16V TFSI S-tronic 3p
A3 Sedan Prestige Plus 1.4 TFSI Flex Tip
TT 1.8 TB 180cv
应该是最终结果

最佳答案

您可以使用删除第一个数字

Sub Validator()
Dim r As Range
Dim s As String
Dim news As String
Dim regex As New RegExp
Dim regex2 As New RegExp
regex.Global = False ' <---- Enabling first match search only (you may also just remove this line)
regex2.Pattern = "\d+(?:\.\d+)?" ' <---- One or more digits, and an optional occurrence of
' a dot and one or more digits right after
Sheet1.Activate
For Each r In Range("B1:B17")
s = r.Value
r.Value = regex2.Replace(s, " ")
Next r

End Sub
请注意 regex.Global默认值为 False ,所以你可以简单地用 regex.Global = False 删除该行.
如果您的数字可以有混合小数分隔符,例如 ., , 使用 regex2.Pattern = "\d+(?:[.,]\d+)?" .

关于选择第一个出现的数字的正则表达式,在循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66064779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com