如何将JavaScript正则表达式及指定JS代码转换为C#?
Converting JavaScript Regex to C#: Methods + Code Conversion
Hey there! Let's walk through how to translate JavaScript regular expressions to C#, then convert your specific code snippet step by step.
Key Conversion Rules
First, here are the core differences and fixes you need to know:
- String Escaping: JavaScript uses regex literals (
/pattern/), but C# represents regex as strings. Use C#'s verbatim strings (prefix with@) to avoid double-escaping backslashes (way easier!). For double quotes in verbatim strings, use two consecutive quotes ("") to escape them. - Regex Flags: JavaScript uses suffix flags like
g(global) ori(case-insensitive). In C#, these are replaced withRegexOptionsenum values (e.g.,RegexOptions.IgnoreCase,RegexOptions.Multiline). - Regex Class: C# uses the
System.Text.RegularExpressions.Regexclass to work with patterns—no direct literal syntax like JS.
Your Code Converted to C#
Here's the equivalent C# code for your JavaScript test() function, with proper regex handling:
using System.Text.RegularExpressions; public static void Test() { // Matches key-value pairs like "key" = "value" var patKeyValue = new Regex(@"""([^""]*)""\s*=\s*""([^""]*)"""); // Note: Swapped .* with [^""]* to avoid greedy matching across quotes (more reliable) // Matches single-line comments (// ...) var patCommentSingle = new Regex(@"//(.*)"); // Matches single-line block comments (/* ... */) var patCommentBlock = new Regex(@"/\*(.*?)\*/"); // Used .*? for non-greedy match to stop at first */ // Matches start of block comments (/* ...) var patCommentStart = new Regex(@"/\*(.*)"); // Matches end of block comments (... */) var patCommentEnd = new Regex(@"(.*)\*/"); }
Quick Notes on the Conversion:
- I used verbatim strings (
@) for all regex patterns to keep them readable (no messy double backslashes). - For the key-value regex, replacing greedy
.*with[^""]*prevents the regex from matching past the closing quote—this is a common reliability tweak that works in both JS and C#. - For the single-line block comment regex,
.*?(non-greedy) ensures it stops at the first*/instead of matching to the last one in the text.
内容的提问来源于stack exchange,提问作者Srinivas M
相关产品推荐
相关产品推荐

