3

I have to use regular expressions in a c# application and I try to use it as a string to use regex.match method. My regular expression is like id="(tt[0-9]+)\|imdb and I convert it to string like "id\"(tt[0-9]+)\\|imdb" but it doesn't work. Do you have any solutions or applications that convert regexes to strings??

1
  • 3
    your string is missing the = is that intentional? Commented Nov 23, 2010 at 15:56

3 Answers 3

4

You can drop the escaping and use a @ sign.

@"id=""(tt[0-9]+)\|imdb"

Note: you have to double the doublequotes

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

Comments

3

Not sure what you are trying to accomplish, so I am going down a different path then the other posts.

The Regex.Match method should take the String you are trying to match against, it sounds like you are attempting to go backwards from a constructed RegEx to a String. If that is the case simply call ToString() on the RegEx to get the passed in expression.

If you are simply trying to get the expression as a String then the pattern var below would so that making use of the @ as mentioned in the other posts. Either way though, the RegEx itself should contain the pattern you want to match against.

  string text = "91919182389348487";
  string pattern = @"id=""(tt[0-9]+)\|imdb";

  Regex r = new Regex(pat, RegexOptions.IgnoreCase);
  Match m = r.Match(text);
  ...

Comments

1

In C#, it is a good idea to add a @ before strings containing reg exps:

 @"id\"(tt[0-9]+)\\|imdb"

Otherwise the regexp engine would only see this string:

  id"(tt[0-9]+)\|imdb

where \| is not recognized the way you want it.

1 Comment

Good advice, not-so-good explanation. In the verbatim string version the \" needs to be changed to "" and the extra backslash in \\| should be removed. But the OP's regex is well formed for a non-verbatim string. I suspect the real problem was the missing =, as @AndrewCox pointed out in his comment.

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.