Pregunta

I have some html files with javascript functions like this

<!-- some content -->
<div conmousedown="My_Function('FirstParamterThatCanBeAnything', '')">
<!-- some content -->
</div>
<!-- some content -->

I would like to be able to use a substitution (http://msdn.microsoft.com/en-us/library/ewy2t5e0(v=vs.110).aspx) to set the second parameter without changing the rest :

<!-- some content -->
<div conmousedown="My_Function('FirstParamterThatCanBeAnything', 'SOMENEWVALUE')">
<!-- some content -->
</div>
<!-- some content -->

the first parameter is an url with random parameters, it's never the same

can someone help me finding a regular expression ?

¿Fue útil?

Solución

From the comments, here's the regex I propose:

(My_Function\((?:[^,']+|("|')(?:(?!\2).)*\2), ')('\))

Breakdown:

(                 # Open 1st Capture group
  My_Function\(   # Match My_Function(
  (?:
    [^,']+        # Match any non comma/quote characters (for numeric param)
  |               # Or
    ("|')         # A quote stored in 2nd Capture group
    (?:(?!\2).)*  # Any character except the quote that matched
    \2            # The quote that matched
  )
  , '             # Match a comma, a space and a single quote
)                 # End 1st Capture group
(                 # Open 3rd Capture group
'\)               # Match single quote and )
)                 # Close 2nd Capture group

regex101 demo

Implementing that in C# will be something a bit like this:

Regex regex = new Regex(@"(My_Function\((?:[^,']+|(""|')(?:(?!\2).)*\2), ')('\))");
str = regex.Replace(text, "$1SOMENEWVALUE$3");

Where text contains the page.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top