簡體   English   中英

在正則表達式中的字符之間獲取字符串

[英]Getting string between characters in Regex

我有一個字符串列表,其輸出如下

      stop = F6, quantity ( 1 )                        // stop 0
      stop = F8, quantity ( 1 )                        // stop 1
      stop = BN, quantity ( 1 )                        // stop 2
      stop = F6, quantity ( 1 )                        // stop 3
      stop = F8, quantity ( 1 )                        // stop 4
      stop = BN, quantity ( 1 )                        // stop 5
      stop = F6, quantity ( 1 )                        // stop 6
      stop = F8, quantity ( 1 )                        // stop 7
      stop = SC, quantity ( 1 )                        // stop 8
etc

使用foreach循環,我正在檢索列表中的每一行,即

`stop = F6, quantity ( 1 )                        // stop 0`

但是我只需要字符F6。 我知道在這種情況下我需要使用正則表達式來檢索f6,但是我不確定該表達式。 從正則表達式的簡短教程中,我嘗試使用下面的代碼來實現此目標,但運氣不好

`Regex.Match(output, @"=\w*,").Value.Replace("\"", "");`

任何幫助,將不勝感激。

您可以使用以下模式:

"=\\s([A-Za-z0-9]{2}),"
//or
"=\\s(\\w+),"

碼:

string str = "stop = F6, quantity ( 1 )  ";
var res = Regex.Matches(str, "=\\s([A-Za-z0-9]{2}),")[0].Groups[1].Value;

我對C#不太了解,但是您使用的是正則表達式: "= (\\w+)," 該正則表達式可獲取=,之間的任何單詞/數字。

在正則表達式中,括號之間的表達式稱為“捕獲組”。 在任何語言中,您都有一些API可以在捕獲組中檢索內容捕獲。 我為C#找到了這個: https : //msdn.microsoft.com/fr-fr/library/system.text.regularexpressions.match.groups(v=vs.110).aspx

因此,用於檢索數據的代碼如下所示:

String pattern = @"=\\s(\\w+),";
MatchCollection matches = Regex.Matches(input, pattern);

foreach (Match match in matches)
{
   Console.WriteLine("Value : {0}", match.Groups[1].Value);
}

為了實時測試您是否正則表達式, https ://regex101.com/非常有用! 使用它可以直觀地查看正則表達式請求在編寫時的作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM