如何在 C# 中使用 Regex 检索选定的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-07-31 17:24:36  来源:igfitidea点击:

How do you retrieve selected text using Regex in C#?

提问by Eldila

How do you retrieve selected text using Regex in C#?

如何在 C# 中使用 Regex 检索选定的文本?

I am looking for C# code that is equivalent to this Perl code:

我正在寻找与此 Perl 代码等效的 C# 代码:

$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = ;}

采纳答案by Patrick

int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)")
Match m = re.Match(s)

if(m.Success)
  indexVal = int.TryParse(m.Groups[1].toString());

I might have the group number wrong, but you should be able to figure it out from here.

我可能把组号弄错了,但你应该可以从这里找出来。

回答by Dillie-O

You'll want to utilize the matched groups, so something like...

你会想要利用匹配的组,所以像......

Regex MagicRegex = new Regex(RegexExpressionString);
Match RegexMatch;
string CapturedResults;

RegexMatch = MagicRegex.Match(SourceDataString);
CapturedResults = RegexMatch.Groups[1].Value;

回答by Jeff Atwood

I think Patrick nailed this one -- my only suggestion is to remember that named regex groups exist, too, so you don't haveto use array index numbers.

我认为帕特里克保密工作做的-我唯一的建议是要记住,命名正则表达式组的存在,也让你不具备在使用数组索引号。

Regex.Match(s, @"Index (?<num>\d*)").Groups["num"].Value

I find the regex is a bit more readable this way as well, though opinions vary...

我发现正则表达式也以这种方式更具可读性,尽管意见各不相同......

回答by andnil

That would be

那将是

int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)");
Match m = re.Match(s);

if (m.Success)
    indexVal = m.Groups[1].Index;

You can also name you group (here I've also skipped compilation of the regexp)

你也可以给你的组命名(这里我也跳过了正则表达式的编译)

int indexVal = 0;
Match m2 = Regex.Match(s, @"Index: (?<myIndex>\d*)");

if (m2.Success)
    indexVal = m2.Groups["myIndex"].Index;

回答by burning_LEGION

int indexVal = 0;
Regex re = new Regex.Match(s, @"(<?=Index: )(\d*)");

if(re.Success)
{
  indexVal = Convert.ToInt32(re.Value);
}