Replace Middle of an attribute value (RegEx)?

L

localhost

I have a string that looks like this:

"init();this.docForm.textBox1.focus
();this.docForm.textBox1.select();"

In this case, I need to replace "textBox1"
with "textBox2". However, the value-to-replace may not
be "textBox1", it could be anything. What kind of RegEx
would I need to replace a value between other parts of a
string (in this case between "docForm." and a ".")?

Thanks.
 
J

Jeffrey Tan[MSFT]

Hi

Based on my understanding, you want to look for all the occurrence of
string between "docForm." and ".", then for each occurrence string, replace
it with "textBox2".
I think you can do like this:

private void button1_Click(object sender, System.EventArgs e)
{
try
{
string
str="init();this.docForm.textBox1.focus();this.docForm.textBox1.select();";
Regex regex=new Regex("docForm.([^.]*)."); //note: the [^.]
standard for the string can not contain ".", () means I make a groups
collection for the string between "docForm." and "."
MatchCollection matches=regex.Matches(str); //find all the
occurrence of Regular expression
string newstr=str;
foreach(Match match in matches) //foreach
occurrence replace it.
{
Regex newregex=new Regex(match.Groups[1].Value);
newstr=newregex.Replace(newstr,"textBox2",1); //the third
parameter 1 means for one occurrence, we only replace once.
}
MessageBox.Show(newstr);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top