简体   繁体   English

从Java到C#的转换有什么问题?

[英]What's wrong with this Java to C# conversion?

i'm trying to convert the following code from Java to C#. 我正在尝试将以下代码从Java转换为C#。

// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");

which I convert as ... 我转换为...

var foo = new Regex(":0 0 0 0(;|})", RegexOptions.IgnoreCase).Replace(foo, "XXXXXXXX");

This compiles but does not work when i run this against the following code... 当我针对以下代码运行此代码时,它将编译但不起作用...

foo = "a {background-position: 0 0 0 0;}\nb {BACKGROUND-POSITION: 0 0;}"

but if I change the regex pattern to :- 但是如果我将正则表达式模式更改为:-

var foo = new Regex("0 0 0 0", RegexOptions.IgnoreCase).Replace(foo, "XXXXXXXX");

it does correctly change the result. 它确实可以正确更改结果。

Now before you go on saying This is a REGEX question, not a Java to C# conversion, question I would like to make the assumption that the regex is valid because it's being used in the following (well known/popular) project with a corresponding unit test that passes. 现在,在继续说这是一个REGEX问题,而不是从Java到C#的转换之前,我想先假设一下该正则表达式是有效的,因为正将其用于以下(众所周知/受欢迎的)项目中,并带有相应的单元测试通过。 Another example of this code as javascript has it coded like ... 此代码的另一个示例是javascript ,其编码方式类似于...

// Replace 0 0 0 0; with 0.
css = css.replace(/:0 0 0 0(;|\})/g, ":0$1");

Notice the missing quotes for the first argument? 注意到第一个参数缺少引号了吗? So I'm wondering if i also haven't converted the java to c# properly. 所以我想知道我是否还没有将Java正确地转换为C#。

There are two problems with your regex at the moment: 您的正则表达式目前有两个问题:

  • You're not closing the bracket (or you weren't before you edited the question) 您没有关闭括号(或者您在编辑问题之前就没有)
  • You're searching for a string starting with ":0" whereas in foo there's a space after the colon 您正在搜索以“:0”开头的字符串,而在foo ,冒号后面有一个空格

This works fine: 这很好用:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string foo = "a {background-position: 0 0 0 0;}\nb "
                   + "{BACKGROUND-POSITION: 0 0;}";
        var regex = new Regex(": 0 0 0 0(;|})", RegexOptions.IgnoreCase);
        string replaced = regex.Replace(foo, "XXXXXXXX");
        Console.WriteLine(replaced);
    }
}

I'd be surprised if the Java version actually worked for your original string, given the "space after colon" problem. 考虑到“冒号后面的空格”问题,如果Java版本实际上可用于您的原始字符串,我会感到惊讶。 You may want to adjust the regular expression to make the space optional: 您可能需要调整正则表达式以使空间可选:

": ?0 0 0 0(;|})"
using System; 
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string f0o = "a {background-position: 0 0 0 1;}\nb " +
                     "{BACKGROUND-POSITION: 0 0;}";

        var regex = new Regex(": 0 0 2 0(;})", vRegexOptions.IgnoreCase);
        string replaced = regex.Replace(foo, "XXXXXXXX");
        Compile.WriteLine(replaced);
    }
} 

This should fix your problem. 这应该可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM