views:

52

answers:

3

Hi,

As you might know,Visual Studio's Find and Replace feature allows us to use Regular Expression but I don't know how to change something like this :

Math.round((document.getElementById('selectedproductPrixdock').value*document.getElementById('addxdock').value)*100)/100

to this one :

(Math.round((document.getElementById('selectedproductPrixdock').value*document.getElementById('addxdock').value)*100)/100).toFixed(2)

There are too much code like this on the page and changing them one by one is a big hassle.

Thanks in advance..

+1  A: 

This doesn't look like a very good candidate for regular expressions, as those are used to find/replace patterns. Deriving a pattern from this text would probably be a waste of time.

I'd just do this:

string s = "...some text...";
string toBeReplaced = "Math.round((document.getElementById('selectedproductPrixdock').value*document.getElementById('addxdock').value)*100)/100";
string replacement = "(" + toBeReplaced + ").toFixed(2)";
string result = s.Replace(toBeReplaced, replacement);

EDIT:

After re-reading your question, knowing each individual ID would make that tougher. Here's a Regex that should work:

string s = "...some text...";
string result = Regex.Replace(s, @"Math\.round\(\(document\.getElementById\('.+'\)\.value*document\.getElementById\('.+'\).value\)*100\)/100", "($0).toFixed(2)");
Doug
A: 

How similar are the things you're trying to match?

If they're all identical except for the inner arguments, then

s/Math.round\(\(document.getElementById\('(.*?)'\).value*document.getElementById\('(.*?)'\).value\)*100\)\/100/\(Math.round\(\(document.getElementById\('$1'\).value*document.getElementById\('$2'\).value\)*100\)\/100\).toFixed\(2\)/g

Replacing $1 and $2 with whatever VS uses to fill in backreferences.

Anon.
A: 

I think you're asking too much of regex in general.

In related news, you would likely have an easier time refactoring if you didn't pack fifty instructions into a single line.

Dave Swersky