i'm trying to convert the following code from Java to 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. Another example of this code as javascript has it coded like ...
// 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.
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
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. 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.
精彩评论