1

I need to convert some old VB.net code to c#, and to speed things up I was planning to use regex.

For instance, in this piece of code:

if (Request.ServerVariables("SERVER_NAME").StartsWith("user"))
        userS = true;

if (Request.ServerVariables("HTTP_X_ORIGINAL_URL") != null && Request.ServerVariables("HTTP_X_ORIGINAL_URL").StartsWith("/contai"))
        UseContai = true;

I want to replace Request.ServerVariables("...") with Request.ServerVariables["..."] I tried using Request.ServerVariables("(.*)") to match it, but it's not working. Any suggestions?

1 Answer 1

2

Parens are a special character in REGEX, as they create a "matching group". So if you'd need to escape them with a backslash (\). You'd also want to escape the period/fullstop since that also has a special meaning in regex:

Request\.ServerVariables\("(.*)"\)

However, this is a pretty liberal match - to make sure you only get through the end perem of the Request.ServerVariables("...") you may instead prefer:

Request\.ServerVariables\("([A-z_]+)"\)

That would give you a match between the quotes of only A-z and an _.

A great resource for you to learn more about Regex is Regexr. It has a live text editor where you can try out different patterns and see how it matches in your example. It also has a "Samples" window that gives you hints about what pieces do.

If you want an easier find/replace (and this is not an elegant regex), you could do more matching groups:

Find: (Request\.ServerVariables)\(("[A-z_]*")\)
Replace: $1[$2]

See it here

3
  • Thanks, but it seems that it matches the full line. Is there anyway to make the "matching ending" after the last ) regexr.com/?387tf
    – Cornwell
    Feb 7, 2014 at 13:30
  • 1
    I was just updating to show why that was :) Try that out.
    – nerdwaller
    Feb 7, 2014 at 13:32
  • Sure thing, I just added a potentially time saving fix for you with the replacement - hope that helps!
    – nerdwaller
    Feb 7, 2014 at 13:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .