【问题标题】:Converting Javascript RegEx to C# Regex将 Javascript 正则表达式转换为 C# 正则表达式
【发布时间】:2018-04-27 06:24:30
【问题描述】:

我有一个 Javascript 正则表达式,可以对句子中的单词进行标记,如下所示:

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

如果像Hello World. 这样输入一个句子,上面的正则表达式将 将其标记为单词:

HelloWorld.

我正在尝试在 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#?

【问题讨论】:

    标签: javascript c# regex


    【解决方案1】:

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

    这里,[^] 在 JS 正则表达式中用于匹配任何字符。您可以将.RegexOptions.Singleline 选项一起使用(然后您将不得不删除RegexOptions.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 在 .NET 正则表达式中可以识别 Unicode,也可以匹配带有一些变音符号的所有 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]";
    

    更多详情

    【讨论】:

    • 它不工作,我收到System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
    • 我没有检查代码,但是正则表达式是可以的。让我添加一个演示。 Here is a C# demo
    • 是的,我需要更改我的正则表达式以使其与 .NET 兼容吗?
    • 要标记一个这样的句子,你可以使用一个你所拥有的正则表达式。现在它的工作方式会有所不同,因为\w\s 在 .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]";
    • @KunalMukherjee 试试this C# demo solution@"[-+]?\d*\.?\d+(\d[-+]?\d+)?|\w+|[^\w\s]" 模式将标记为数字、单词和单个标点符号/符号字符。
    猜你喜欢
    • 2011-10-02
    • 2023-03-09
    • 2016-09-13
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多