2

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.

I would like to change the following strings:

  • John;-4;5

  • John;20;15

  • John;-255;2

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

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

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

Your help is much appreciated.

3
  • Regular expressions are not wildcards. They are a very different beast. Commented May 16, 2013 at 14:56
  • 1
    John;-?\d+;-?\d+ :p Commented May 16, 2013 at 15:03
  • What does newString look like for each of the samples given a specific newValue? Commented May 16, 2013 at 16:04

3 Answers 3

7

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

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

will become

John;newValue
Sign up to request clarification or add additional context in comments.

Comments

1

Use a multiline regex with the following expression

;(.)[-+]?\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)

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.