1

I'm converting a project from java to C#. I have no idea what the equivalence of following regular expression would be in C#.

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

This is the java code:

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

and it works for ( X=Customer rating 1.0/5.0 ). But this is the C# code:

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

and it doesn't work for ( X=Customer rating 1.0/5.0 ).I mean (Matches.count) is always 0 for ( X=Customer rating 1.0/5.0 )

Please help me if you have any ideas.

Thank you

2 Answers 2

2

You don't need to escape the baclslash one more time if the regex was present within a verbatim string.

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

And also escape all the dots present in your regex, since dot matches any character not only a literal dot.

Inside a verbatim string, \\d matches a literal backslash and a character d. So your regex searches for a backslash and a literal d. since there isn't any, your regex got failed.

Sign up to request clarification or add additional context in comments.

1 Comment

or use this "Customer rating (?<rating>\\d\\.\\d)/5\\.0" without @
0

Solution is to use @ varbitm literal to define regex with escape sequences like back slash \

So code would be :

  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);
        }
   }

Here is the regex explanation : https://regex101.com/r/qS0qG3/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.