【问题标题】:VB.NET regular expression replace stringVB.NET 正则表达式替换字符串
【发布时间】:2013-05-16 14:53:15
【问题描述】:

我有一个字符串,我需要在 VB.Net 代码中使用通配符来替换它。 我发现我可能需要使用正则表达式,但我是新手。

我想更改以下字符串:

  • John;-4;5

  • John;20;15

  • John;-255;2

其中-4;5 等是将字符串的更改部分转换为newValue

我使用了标准的字符串替换,但这似乎不起作用:

newString = oldString.Replace(oldString & ";" & "*" & ";" & "*", "newValue")

非常感谢您的帮助。

【问题讨论】:

  • 正则表达式是not通配符。他们是一个非常不同的野兽。
  • John;-?\d+;-?\d+ :p
  • 给定特定 newValue 的每个样本的 newString 是什么样的?

标签: regex vb.net replace


【解决方案1】:

试试:

ResultString = Regex.Replace(SubjectString, "(-*\d+;*)+", "newValue")

这将替换任何出现的数字(带或不带 -ve 符号)后跟 ;或不。因此您的样本数据

John;-4;5
John;20;15
John;-255;2
John;123;234;5;32;45;543

会变成

John;newValue

【讨论】:

    【解决方案2】:

    使用带有以下表达式的多行正则表达式

    ;(.)[-+]?\b[0-9].?[0-9]+\b

    所以也许像这样用空白字符串替换所有实例,我还没有测试过,因为我现在不能,但是如果失败了,那么用单行替换多行

    Dim SourceString as string = "John;-4;5" & vbcrlf & "John;20;15"
    Dim ReplaceString as string = ""
    Dim result As String =   Regex.Replace(SourceString,";(.*)[-+]?\b[0-9]*\.?[0-9]+\b",ReplaceString,RegexOptions.IgnoreCase or RegexOptions.Multiline)
    

    【讨论】:

      【解决方案3】:

      你可以试试这个

      newString = 
      oldString.Replace(oldString,"newValue").replace(";","NewVal").replace("*","Newval)
      

      这只会替换旧字符串中的字符

      我会试试这个:

      dim val as string = "John;-4;5" ' Or any other string like this
      
      Dim arr() As String = val.Split(";")
      
      'manipulate string from here 
      
      'arr(0) is John
      'arr(1) is -4
      'arr(2) is -5
      

      然后构建你的新值字符串

      val = arr(0) & ";" & "newval" & ";" & "newVal"
      

      【讨论】:

        猜你喜欢
        • 2018-07-13
        • 2017-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-30
        相关资源
        最近更新 更多