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??
-
3your string is missing the = is that intentional?Andrew Cox– Andrew Cox2010-11-23 15:56:16 +00:00Commented Nov 23, 2010 at 15:56
3 Answers
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
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
\" 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.