• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 432
  • Last Modified:

Use Regex to identify if text is inside quotes

Can someone advise the Regex expression to allow replacement of text if it doesn't appear inside quotes. For example if I have the following

Dim Var1, Var2, Var3 As Integer
CallSomeMethod(Var1, Var2, Var3, "Var1", "Var2", "Var3")

How do I replace Var2 with another name, say NewVar, so that the text appears as follows -

Dim Var1, NewVar, Var3 As Integer
CallSomeMethod(Var1, NewVar, Var3, "Var1", "Var2", "Var3")
  • 2
1 Solution
To exclude quoted variables, your expression should exclude character 34 ascii = 22 hex

Use the same to exclude "(", [A-Z|0-9], to avoid replacement of strings like "Function Var2(...)" or strings like Var21
Stephen_CurleAuthor Commented:
I don't think this is quite what I need and the example I gave was probably too basic. What if I wanted to replace Var2 in the following

CallSomeMethod(Var1, Var2, "Var1, Var2", "Don't replace Var2 here", Var2, "Don't replace Var2 here")

so revised text appears

CallSomeMethod(Var1, NewVar, "Var1, Var2", "Don't replace Var2 here", NewVar, "Don't replace Var2 here")

The sort of thing I'm looking for (if it's possible) is to be able to right code such as

RevisedText = Regex.Replace(Text, NotInQuotes & "Var2", "NewVar")

where I need to know the correct Regex expression for NotInQuotes that will work in all cases.
Bob LearnedCommented:
1) That requirement appears to be a little too complex for a single regular expression.

2) My initial thoughts are to break that string up by comma, but you probably have more of examples of where that wouldn't work:

  "Var1, Var2"
  "Don't replace Var2 here"
   "Don't replace Var2 here"

   This way, you could check if the string starts with quote, and skip those, but do a simple Replace function.

Stephen_CurleAuthor Commented:
I think you can get it to work by splitting by " and then changing every other item.

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now