Reputation: 95
I am using Regex to retrieve a paragraph. My paragraph in my string variable contains the beginning letter, G. and it ends with a variable, @Variable.
What pattern would I use to use to grab that paragraph? I was using the code below but I think I am really off.
Regex.Match(paragraph, @"\G. .*\@Variable$");
Upvotes: 2
Views: 2492
Reputation: 19842
I think this is what you want (if I'm understanding your requirements):
string regex = @"G.+" + variable;
Regex.Match(paragraph, regex);
A couple of things to note, you have to be careful what is in the variable
if it contains things like \
that is going to mess up your regex. There are "reserved" characters in regex that you have to beware of so as not to cause problems.
Also, instead of .*
I used .+
which means "Between one and unlimited times" rather than "Between zero and unlimited times" so it requires that there is at least one other character in your "paragraph". You may wish to add something like .{10,}
which would establish a minimum of 10 characters, depending on your needs.
Upvotes: 1
Reputation: 30882
It would be something like this:
string regex = @"G.+" + variable.ToString()
Regex.Match(paragraph, regex);
While you're at it grab a copy of Expresso - makes tasks like this much easier.
Upvotes: 2
Reputation: 3493
I think you might be looking for something like this:
Regex.Match(paragraph, string.Format(@"^G.*?{0}$", yourVariableHere));
Upvotes: 1