首页 文章

VB.Net Regex替换括号内的双引号

提问于
浏览
2

我一直在试着想出这个问题 . 我需要在一组括号内替换双引号 . 我的示例下面显示了单引号,但我仍然遇到问题

这对我有用 -

Dim input As String = "This is my ['Test'] that works"
Dim output As String = Regex.Replace(input, "(?<=my.*)'(?=.*that)", "?")

生成此字符串 - This is my [?Test?] that works .

但如果我尝试这是追加而不是替换单引号 -

Dim input As String = "This is my ['Test'] that works"
Dim output As String = Regex.Replace(input, "(?<=[.*)'(?=.*])", "?")

产生这不是我想要的 - This is my ['?Test'?] that works .

你可以看到Regex.replace附加了?单引号后,但我需要它用?替换单引号 . 我很难过 .

1 回答

  • 1

    要匹配方括号内的所有单引号,您需要转义开头 [ ,否则它将被视为特殊字符(打开字符类):

    (?<=\[[^][]*)'(?=[^][]*])
    

    此外,您需要将字符限制为与 [] 不同 . 为此,您可以使用 [^][] 否定字符类(这将匹配 [] 以外的任何字符) .

    regex demo

    enter image description here

相关问题