简体   繁体   中英

How to use Regex to search only inside strings (between double quotations)

This is a very basic regex question.

Suppose I have lots of string constants throughout my code (enclosed with double quotations). Some of these strings contain class substring like the "declassification" constant in this example:

public class Names {
    string text = "declassification";
    string classified = "foo";
}

All 3 lines contain class , but only "declassification" is interesting to me because it's between double quotations.

What I did:

I found this question: Regex.Matches c# double quotes . It tells me how to get everything in a double quotations like this: \\"(.*?)\\" . But I need to search for a specific string anywhere between the double quotations.

This question: Extract the values between the double quotes using regex also tells me to use this: @"""New[^"":]+:[^""]+""" which doesn't work for me.

Find Results:

Wrong:

public class Names {

string text = "de class ification";

string class ified = "foo";

Expected:

string text = "de class ification";

Question:

When I search with Visual Studio Find Tool , how can I only search through the string constants and ignore the rest of the files?

Hint: .* means any number of any characters

With regex if you search \\"class\\" it exactly matches "class" .

To match "<anything>class<anything>" add any number of any characters before and after class :

\".*class.*\"

To match '<anything>class<anything>' as well (such as javascript strings) use this:

["'](.*)(class)(.*)["']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM