VB.NET 正则表达式替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16590773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:36:50  来源:igfitidea点击:

VB.NET regular expression replace string

regexvb.netreplace

提问by meryloo

I have got a string that I need to replace by using wildcards in a VB.Net code. I found out that I may need to use the Regular expressions but I am new to it.

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

I would like to change the following strings:

我想更改以下字符串:

  • John;-4;5

  • John;20;15

  • John;-255;2

  • John;-4;5

  • John;20;15

  • John;-255;2

where the -4;5etc are the changing parts of the string into newValue

其中-4;5etc 是字符串的变化部分newValue

I used a standard string replace but that does not seem to work:

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

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

Your help is much appreciated.

非常感谢您的帮助。

回答by ajakblackgoat

Try:

尝试:

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

This will replace any occurrence of numbers (with or without -ve sign) followed by ; or not. Therefore your sample data of

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

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

will become

会变成

John;newValue

回答by Andre Pageot

Use a multiline regex with the following expression

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

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

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

so maybe something like this to replace all instances with a blank string, I havent tested this because i cant at the moment but if this fails then replace the multiline with singleline

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

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)

回答by Pakk

You could always try this

你可以试试这个

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

this will althrough only replace chars in oldstring

这将始终只替换旧字符串中的字符

I would try this :

我会试试这个:

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

then build your new value string

然后构建您的新值字符串

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