我有以下字符串
我真正想要做的是把里雅斯特MED (第一串),里雅斯特(第二弦),宁波东太平洋(第三弦)和阿加伊特奥多诺德(第四弦)作为一个叫做开放港的组。通常在2013年与原油/原油/原油之间有1至4个单词。
这就是我到目前为止尝试过的https://regex101.com/r/mYevqd/1。
但这很容易出错,因为我只假设开放端口组的单词由一个或两个空格max分隔,即wrong.If,我尝试放置\s*,然后捕获第一个干净的字母,这是错误的。还有什么更好的吗?
发布于 2019-01-05 18:57:49
你可以用这个简化你的正则表达式,
^(?<YearBuilt>\d{4})\s+(?<OpenPort>.*)\s+(?<LastCargos>[^ ]+)$由于字符串中的第一件事是一年,因此使用\d{4},所以您最不想分组的是类似于这个clean/crude/crude的东西,您可以将它捕获为这个[^ ]+ (任何东西,但不是空格),然后可以用.*捕获其示例类似于这个Ningbo East Pacific的中间文本。
让我知道,如果这对你的其他字符串工作良好。
发布于 2019-01-05 19:02:47
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
*/发布于 2019-01-05 19:18:32
如果你允许我..。
并不是每个基于文本的问题都需要一个Regex来解决。通常,您只需使用Split()和其他一些目标驱动的语句来达到目标。这比试图击败有时不可读的Regex提交要容易得多(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;添加到C#文件后可用。
https://stackoverflow.com/questions/54055137
复制相似问题