You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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) or i (case-insensitive). In C#, these are replaced with RegexOptions enum values (e.g., RegexOptions.IgnoreCase, RegexOptions.Multiline).
  • Regex Class: C# uses the System.Text.RegularExpressions.Regex class 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:41:04