Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace the nth regex group with a new String in .net?

Tags:

.net

regex

I have a pipe delimited string like this:

blah|blah|blah|blah|blah|blah|blah|blah|blah|oldDate|blah|blah|

I would like replace the content of the 10th section with a new Date. I am able to match the the old date with the the following code:

'create a group with the first 9 non-pipes followed by a pipe, a group with the old date followed by a pipe, and sub-group of just the old date.
Dim pipeRegEx As New RegularExpressions.Regex("(([^\|]*\|){9})(([^\|]*)\|)")

'the sub-group is the 4th group ordinal in the match GroupCollection
Dim oldDate as String=pipeRegEx.Match(strMessage).Groups(4).Value

However, I can't figure out how to repace that group with new text. I have tried:

pipeRegEx.Replace(strMessage, "$4", newDate) 'where newDate is a string var

But that returns the original message like it was unable to find the 4th group. I am unable to do a string replace with the matched date since there are multiple dates in the string (orderDate, receivedDate, etc) and its possible to match on one of those by accident.

Does anyone know how to replace this text?

Thanks in advance for any help.

like image 953
dsrekab Avatar asked Feb 27 '23 05:02

dsrekab


2 Answers

There's no apparent reason to use a regex here, use strMessage.Split('|').

string str = "blah|blah|blah|blah|blah|blah|blah|blah|blah|oldDate|blah|blah";
string[] tokens = str.Split('|');
tokens[9] = "newDate";
string newStr = String.Join("|", tokens);

If you do need to use a regex, consider using Regex.Replace(string, string):

pipeRegEx.Replace(strMessage, "$2" & newDate & "|") 

Replace works the other way around - you use groups to keep tokens in your string, not to move them out.

like image 181
Kobi Avatar answered Feb 28 '23 18:02

Kobi


So what you are doing is this, you are calling a Shared version of the RegEx library on your regex, you aren't actually using your regex to find the match, it is using the "$4" to find a match, which it isn't. This is why you are getting your original string back.

I would do something like this to get the appropriate group replaced with the new date

Dim matchedGroups As New System.Text.RegularExpressions.Matches = pipeRegEx.Matches(strMessage)

matchedGroups(9) = "new Date"

And then just put your list back together.

like image 42
msarchet Avatar answered Feb 28 '23 18:02

msarchet