【问题标题】:Finding and replacing a Substring using Regex使用正则表达式查找和替换子字符串
【发布时间】:2016-01-21 19:27:24
【问题描述】:

我正在尝试使用 Regex for Excel 替换字符串中的子字符串“AV-”。我创建了以下函数,但它没有找到或替换匹配项

Sub simpleRegex()
Dim strPattern As String: strPattern = "[AV-]{AV-}"
Dim strReplace As String: strReplace = "ZS-"
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range

Set Myrange = ActiveSheet.Range("E" & (ActiveCell.Row))

If strPattern <> "" Then
    strInput = Myrange.Value
    strReplace = ""

    With regEx
        .Global = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.Test(strInput) Then
        ActiveSheet.Range("E" & (ActiveCell.Row)).Value = (regEx.Replace(strInput, strReplace))
    Else
        MsgBox ("Not matched")
    End If
End If

结束子

【问题讨论】:

  • 我假设您正在尝试学习一些东西,因为这可以通过 vba 中的一行来完成 Myrange.Replace "AV-", "ZS-", xlPart, , True
  • 很难说输入/输出要求是什么,但您可以使用 ResultString = Regex.Replace(SubjectString, "(AV-)(.*)", "ZS-$2-TRAILING", RegexOptions.Multiline) 之类的东西或 Scott 提到的东西。

标签: regex excel replace


【解决方案1】:

如果没有样本输入/输出,您还不清楚您想做什么。但是,如果您只想将字符串“AV-”替换为“ZS-”,则您的模式应该是“AV-”。

另外,如果您不知道,有一些正则表达式测试器网站可以帮助您创建/测试您的正则表达式模式,因为复杂的模式会变得非常难以阅读。我推荐的一个站点是https://regex101.com/。请记住,不同语言对正则表达式的实现并不相同,但它至少应该可以帮助您接近。

【讨论】:

  • 嗯,是的,这基本上就是我想要做的。感谢一百万,并提供链接。
猜你喜欢
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 2019-04-17
  • 2012-03-28
  • 2020-12-22
相关资源
最近更新 更多