如何用单个正则匹配含指定关键词的引号内完整字符串?
Great question—sifting through 1700+ matches just to filter for the ones with your keyword is totally inefficient. Instead, we can build a regex that directly targets only the quoted strings containing your keyword, cutting down the number of matches you need to process drastically.
Basic Regex Solution (No Escaped Quotes)
If your input doesn’t include escaped quotes (like \" inside a double-quoted string), this simple regex will get the job done:
"[^"]*example-a[^"]*"
Let’s break down the components:
": Matches the opening double quote.[^"]*: Captures any character except a double quote, zero or more times (covers everything before your keyword).example-a: Your exact target keyword (swap this out for your actual keyword).[^"]*: Again captures non-quote characters after the keyword.": Matches the closing double quote.
Handling Regex Special Characters in Your Keyword
If your keyword might have regex-reserved characters (like ., *, or +), use Regex.Escape() to avoid unexpected behavior. Here’s how to implement this in C#:
string targetKeyword = "example-a"; string input = "Your input string with many quoted parts like \"/tutorial/example/example-a/\" and others."; // Escape the keyword to safely handle regex special characters string regexPattern = $"\"[^\"]*{Regex.Escape(targetKeyword)}[^\"]*\""; MatchCollection relevantMatches = Regex.Matches(input, regexPattern); // Now you only iterate through matches that actually contain your keyword foreach (Match match in relevantMatches) { Console.WriteLine(match.Value); // Outputs: "/tutorial/example/example-a/" }
Handling Escaped Quotes (Advanced Case)
If your quoted strings can include escaped quotes (e.g., "She said \"hi\" example-a"), the basic regex will break because it stops at the first escaped quote. Use this more robust version instead:
"((?:\\.|[^"\\])*)example-a((?:\\.|[^"\\])*)"
This works by:
(?:\\.|[^"\\])*: Matches either an escaped character (\\.) or any character that’s not a quote or backslash, zero or more times. This correctly skips over escaped quotes inside the string.
Why This Is Better
By embedding your keyword directly into the regex, you avoid capturing every single quoted string. The MatchCollection will only include the strings you care about, so you skip the costly step of filtering through hundreds or thousands of irrelevant matches.
内容的提问来源于stack exchange,提问作者TimAlonso

