C# 如何使用正则表达式从字符串中剪切出下面的模式?

C# 如何使用正则表达式从字符串中剪切出下面的模式?,c#,.net,regex,visual-studio-2010,C#,.net,Regex,Visual Studio 2010,我有一个字符串,它的单词“TAG”后跟一个整数、下划线和另一个单词 例如:“TAG123_样本” 我需要剪切“TAGXXX_”模式,只获取单词样本。这意味着我必须剪切单词“TAG”和整数,后跟和下划线 我编写了以下代码,但它不起作用。我做错了什么?我该怎么做?请给我一些建议 static void Main(string[] args) { String sentence = "TAG123_Sample"; String pattern=@"TAG[^\

我有一个字符串,它的单词“TAG”后跟一个整数、下划线和另一个单词

例如:“TAG123_样本”

我需要剪切“TAGXXX_”模式,只获取单词样本。这意味着我必须剪切单词“TAG”和整数,后跟和下划线

我编写了以下代码,但它不起作用。我做错了什么?我该怎么做?请给我一些建议

static void Main(string[] args)
    {
        String sentence = "TAG123_Sample";
        String pattern=@"TAG[^\d]_";
        String replacement = "";
        Regex r = new Regex(pattern);
        String res = r.Replace(sentence,replacement);
        Console.WriteLine(res);
        Console.ReadLine();
    }
您当前正在求反(匹配而不是一个数字),需要按如下方式修改正则表达式:

String s = "TAG123_Sample";
String r = Regex.Replace(s, @"TAG\d+_", "");
Console.WriteLine(r); //=> "Sample"
说明

TAG      match 'TAG'
 \d+     digits (0-9) (1 or more times)
 _       '_'
您当前正在求反(匹配而不是一个数字),需要按如下方式修改正则表达式:

String s = "TAG123_Sample";
String r = Regex.Replace(s, @"TAG\d+_", "");
Console.WriteLine(r); //=> "Sample"
说明

TAG      match 'TAG'
 \d+     digits (0-9) (1 or more times)
 _       '_'

您可以为此使用
String.Split

string[] s = "TAG123_Sample".Split('_');
Console.WriteLine(s[1]);

您可以使用
String.Split
进行此操作:

string[] s = "TAG123_Sample".Split('_');
Console.WriteLine(s[1]);

试试看,这在这种情况下肯定有效:

resultString = Regex.Replace(sentence , 
    @"^   # Match start of string
    [^_]* # Match 0 or more characters except underscore
    _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);

在这种情况下,请尝试以下方法:

resultString = Regex.Replace(sentence , 
    @"^   # Match start of string
    [^_]* # Match 0 or more characters except underscore
    _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);

如果字符串包含1个下划线,并且需要在其后获取子字符串,则不需要正则表达式

以下是一种基于
子字符串
+
索引的方法:

var res = sentence.Substring(sentence.IndexOf('_') + 1); // => Sample

请参见

如果字符串包含1个下划线,并且需要在其后获取子字符串,则不需要正则表达式

以下是一种基于
子字符串
+
索引的方法:

var res = sentence.Substring(sentence.IndexOf('_') + 1); // => Sample
请参见

尝试以下操作:
@“TAG\d+\uuquo;
beacuse
[^\d]
可能只是说“没有数字会跟在标记后面”,所以只需使用表示“多个数字”的\d+,尝试以下操作:
@“TAG\d+\uquo;
beacuse
[^\d]
可能只是说“没有数字会跟在标记后面”,所以只需使用表示“多个数字”的\d+