[英]How can I cut out the below pattern from a string using Regex?
我有一個字符串,其中包含單詞“ TAG”,后跟一個整數,下划線和另一個單詞。
例如:“ TAG123_Sample”
我需要剪切“ TAGXXX_”模式,僅獲得單詞Sample。 意味着我將必須剪切單詞“ 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.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);
如果您的字符串包含1個下划線並且您需要在其后得到一個子字符串,則不需要正則表達式。
這是基於Substring
+ IndexOf
的方法:
var res = sentence.Substring(sentence.IndexOf('_') + 1); // => Sample
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.