Share via


find and replace 'part' of a string between two markers....

Question

Friday, September 25, 2009 1:58 PM

I have a string that may have 'unknown' characters between two markers...

example: str_MyString = "other stuff in this string [marker_start]alongstringofsomething[marker_end] other stuff in this string"

Can I run some type of replace command that replaces 'everything' between [marker_start] and [marker_end] even without knowing exactly what is in it?

example: change str_MyString

from....

"other stuff in this string [marker_start]alongstringofsomething[marker_end] other stuff in this string"

to....

"other stuff in this string [marker_start]the replacement text[marker_end] other stuff in this string"

All replies (7)

Friday, September 25, 2009 2:12 PM ✅Answered

 Yuo can use RegEx:

        Regex x = new Regex("(\\[marker_start\\])(.*?)(\\[marker_end\\])");
        string s = "other stuff in this string [marker_start]alongstringofsomething[marker_end] other stuff in this string";
        string repl = "the replacement text";       
        string Result = x.Replace(s, "$1"+repl+"$3");

 


Saturday, September 26, 2009 2:36 AM ✅Answered

if you give names on groups, the result should be more accurate:

        Regex x = new Regex("(?<start>\[marker_start\])(.*?)(?<end>\[marker_end\])");
        string s = "[marker_start]aet hi ng[marker_end] other stuff in this string [marker_start]alongstringofsomething[marker_end] other stuff in th[marker_start]alosomething[marker_end] is string";
        string repl = "1sometext";
        string Result = x.Replace(s, "${start}" + repl + "${end}");


Friday, September 25, 2009 2:32 PM

awsome.... works great... thanks!


Friday, September 25, 2009 4:04 PM

Follow-Up Question.....

why are the $1 and $3 needed?


Friday, September 25, 2009 4:14 PM

 $1 represent [marker_start] and $2 = [marker_end]

read more here:

http://weblogs.asp.net/rosherove/pages/6946.aspx

http://www.knowdotnet.com/articles/regereplacementstrings.html


Friday, September 25, 2009 4:51 PM

thanks...

my problem is that I have an incrementer that changes the string and the string may have a 2,3,etc.. at the beginning...

example: [start_marker]1sometext[end_marker]

and the replace code changed the above to....

$12thenewtext[end_marker]

... removing the [start_marker]


Tuesday, September 29, 2009 1:08 PM

Works great.... thanks!!