代码之家  ›  专栏  ›  技术社区  ›  Kunal Mukherjee

将Javascript正则表达式转换为C#正则表达式

  •  3
  • Kunal Mukherjee  · 技术社区  · 8 年前

    我有一个Javascript正则表达式,用于标记来自以下句子的单词:

    /\\[^]|\.+|\w+|[^\w\s]/g

    如果输入一个句子 Hello World. 上述正则表达式将 将其标记为文字:

    Hello ,则, World ,则, .

    我试图用C#转换上面的正则表达式,但它无法将其分组。我已尝试删除 / 以及 \g 从开始和结束分别,以使其兼容。NET正则表达式引擎。但它仍然不起作用。

    下面是我正在尝试的C代码:

    public static void Main()
    {
            string pattern = @"\\[^]|\.+|\w+|[^\w\s]";
            string input = @"hello world.";
    
            foreach (Match m in Regex.Matches(input, pattern, RegexOptions.ECMAScript))
            {
                Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
            }
    }
    

    谁能帮我把上面的正则表达式转换成C#?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Wiktor Stribiżew    8 年前

    请注意 RegexOptions.ECMAScript 只需确保速记字符类(此处, \w \s )仅匹配ASCII字母、数字和空格。您不能期望此选项“转换”整个模式以在中使用。NET正则表达式库。

    在这里 [^] JS正则表达式中使用了构造来匹配任何字符。您可以使用 . 使用 RegexOptions.Singleline 选项(然后是您 必须 删除 RegExceptions。ECMAScript 选项)而不是 [^] ,或仅使用 [\s\S] 要匹配任何字符:

    public static void Main()
    {
            string pattern = @"\\.|\.+|\w+|[^\w\s]";
            string input = @"hello world.";
    
            foreach (Match m in Regex.Matches(input, pattern,  RegexOptions.Singleline))
            {
                Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
            }
    }
    

    请参见 C# demo ,其输出:

    'hello' found at index 0.
    'world' found at index 6.
    '.' found at index 11.
    

    笔记 : \w \s 中支持Unicode。NET正则表达式,也可以将所有Unicode字母与一些音调符号进行匹配。如果只想处理ASCII,请使用

    string pattern = @"\\.|\.+|[A-Za-z0-9_]+|[^A-Za-z0-9_\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]";
    

    更多详细信息