[英]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.
我的字符串变量中的段落包含开头的字母G,并以变量@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$");
我认为您可能正在寻找这样的东西:
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. 需要注意的几件事,如果
variable
包含\\
东西会弄乱您的正则表达式,则必须小心该variable
中的内容。 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. 您可能希望添加类似
.{10,}
内容,根据您的需要,该名称至少可以包含10个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.