![](/img/trans.png)
[英]Using regex to ignore an unknown word that is situated between two known words
[英]Regex - catch unknown number of words in between
我有以下字符串
我實際上想要做的是嘗試將的里雅斯特MED(第一串),的里雅斯特(第二串),寧波東太平洋(第三串)和agioi theodoroi med(第四串)作為一個稱為開放端口的組。 通常在 2013 年日期之間有 1 到 4 個單詞,例如和原油/原油/原油。
這是我迄今為止嘗試過的https://regex101.com/r/mYevqd/1 。
但這很容易出錯,因為我只假設開放端口組的單詞最多由一個或兩個空格分隔,這是錯誤的。如果我嘗試放置 \\s* 然后將捕獲 clean 的第一個字母,這是錯誤的。 有什么更好的嗎?
你可以用這個簡化你的正則表達式,
^(?<YearBuilt>\d{4})\s+(?<OpenPort>.*)\s+(?<LastCargos>[^ ]+)$
由於您在字符串中的第一件事是一年,因此使用\\d{4}
並且您想要分組的最后一件事是這樣的clean/crude/crude
,您可以將其捕獲為[^ ]+
(任何但不是空格) 然后可以用.*
捕獲像Ningbo East Pacific
這樣的樣本的中間文本
讓我知道這對於其他字符串是否適合您。
var strings = new[] {
"2011 Trieste MED clean/crude/crude",
"2013 Trieste fo/crude/crude",
"2013 Ningbo East Pacific cca/cf/ce",
"2014 Agioi theodoroi MED cde/fo/ce"
};
var pattern = @"^\d+\s+(.+)(?=\s+.*?/)";
foreach (var s in strings)
{
var match = Regex.Match(s, pattern);
if (match.Success)
WriteLine(match.Groups[1].Value);
else
WriteLine("No matches found.");
}
/*
Output:
Trieste MED
Trieste
Ningbo East Pacific
Agioi theodoroi MED
*/
如果你允許我...
並非每個基於文本的問題都需要拋出正則表達式。 很多時候你可以只使用例如Split()
和其他一些目的驅動的語句來達到你的目標。 這比試圖擊敗有時無法閱讀的正則表達式提交要容易得多(並且在 6 個月后閱讀)。
就是這樣:
public static void Main()
{
var strings = new[] {"2011 Trieste MED clean/crude/crude",
"2013 Trieste fo/crude/crude",
"2013 Ningbo East Pacific cca/cf/ce",
"2014 Agioi theodoroi MED cde/fo/ce"};
foreach (var s in strings)
Console.WriteLine(GetName(s));
}
public static string GetName(string s)
{
var allWords = s.Split(' ');
var nameWords = allWords.Skip(1).Take(allWords.Length - 2);
return string.Join(" ", nameWords);
}
Skip()
和Take()
是 Linq 的擴展方法, using System.Linq;
添加后可用using System.Linq;
到 C# 文件。
查看它正在運行: https : //dotnetfiddle.net/FTBcfC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.