在等号后替换该行上的所有内容

时间:2012-05-21 13:26:05

标签: regex replace vb.net-2010

在VB 2010中使用它:

Imports System.Text.RegularExpressions

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim lines() As String = IO.File.ReadAllLines("filename.txt")
        Dim foundIndex As Integer = Array.FindIndex(lines, Function(l) l.StartsWith(TextBox1.Text)) 'assuming TextBox1.Text = the part of the line before the =
        lines(foundIndex) = Regex.Replace(lines(foundIndex), "(?<=" & TextBox1.Text & "=)\d+", TextBox2.Text) 'TextBox2.Text is the replacement number
        Stop
        'to rewrite the file:
        'IO.File.WriteAllLines("filename.txt", lines)
    End Sub
End Class

...但每次保存文本文件时,它会在等号后添加数字。

我希望它在等号后替换该行上的所有内容。

1 个答案:

答案 0 :(得分:2)

我执行了你的代码并且它没有改变:

Sub Main
     Dim lines() As String = IO.File.ReadAllLines("c:\temp\filename.txt")
     lines.Dump()
        Dim foundIndex As Integer = Array.FindIndex(lines, Function(l) l.StartsWith("blah")) 'assuming TextBox1.Text = the part of the line before the =
        foundIndex.Dump()
        lines(foundIndex) = Regex.Replace(lines(foundIndex), "(?<=blah=)[\d.e+]+", "replaced") 'TextBox2.Text is the replacement number
        IO.File.WriteAllLines("c:\temp\filename.txt", lines)
End Sub

如果文件是

test=456
blah=456
blah=just

它将成为

test=456
blah=replaced
blah=just

这是你想要的吗?

更新1

我替换了

"(?<=blah=)\d+"

使用

"(?<=blah=)[\d.]+"

更新2

关于像“1e + 007”这样的字符串的问题。与“=”之后的字符串匹配的部分当前是[\ d。]

请记住,小数点像3.25的数字有问题吗?通过添加“。”解决了这个问题。字符类[\ d]所以它变成[\ d。] 现在任何数字都是“\ d”和“。”。会匹配。

新问题以同样的方式解决。现在“e”和“+”也应匹配。得到它?所以字符类现在变成[\ d.e +]

试一试,让我知道它是怎么回事。

现在还应该清楚如何修改正则表达式以匹配“BGS_LOGO.BIK”如果你能解决这个问题你就能理解正在发生的事情。