【问题标题】:Converting regular expression from java to .Net将正则表达式从 java 转换为 .Net
【发布时间】:2015-05-16 20:51:54
【问题描述】:

我正在将项目从 java 转换为 C#。我不知道在 C# 中遵循正则表达式的等价性是什么。

The regular expression : Customer rating (?<rating>\d.\d)/5.0
The java string : "Customer rating (?<rating>\\d.\\d)/5.0"

这是java代码:

private static final Pattern ratingPattern = Pattern.compile("Customer rating (?<rating>\\d.\\d)/5.0");
...
m = Retriever.ratingPattern.matcher(X);
if (m.matches()) {
...
}

它适用于(X=客户评分 1.0/5.0)。但这是 C# 代码:

static Regex rx = new Regex(@"Customer rating (?<rating>\\d.\\d)/5.0");
...
MatchCollection matches = rx.Matches(X);
if (matches.Count > 0)
{
...
}

它不适用于 (X=Customer rating 1.0/5.0)。我的意思是 (Matches.count) 对于 (X=Customer rating 1.0/5.0) 始终为 0

如果您有任何想法,请帮助我。

谢谢

【问题讨论】:

    标签: java c# regex


    【解决方案1】:

    如果正则表达式存在于逐字字符串中,则无需再次转义反斜杠。

    @"Customer rating (?<rating>\d\.\d)/5\.0"
    

    并且还要转义正则表达式中存在的所有点,因为点匹配任何字符,而不仅仅是文字点。

    在逐字字符串中,\\d 匹配文字反斜杠和字符 d。因此,您的正则表达式搜索反斜杠和文字 d。因为没有,所以你的正则表达式失败了。

    【讨论】:

    • 或者使用这个"Customer rating (?&lt;rating&gt;\\d\\.\\d)/5\\.0"而不使用@
    【解决方案2】:

    解决方案是使用@ varbitm 文字来定义带有转义序列的regex,例如反斜杠\

    所以代码是:

      Regex rx = new Regex(@"Customer rating (?<rating>\d\.\d)\/5\.0"); // <= Updated and cleaned regex
    
      MatchCollection matches = rx.Matches("(X=Customer rating 1.0/5.0)");
    
       if (matches.Count > 0)
       {
            Console.WriteLine("Matched :" );
    
            // Get the match output 
            foreach (Match item in matches)
            {
                 Console.WriteLine(item.Value);
            }
       }
    

    这里是regex的解释:https://regex101.com/r/qS0qG3/1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多