简体   繁体   中英

REGEX C# (Matching beginning and ending word)

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$");

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.

我认为您可能正在寻找这样的东西:

Regex.Match(paragraph, string.Format(@"^G.*?{0}$", yourVariableHere));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM