[英]Get numbers after a specific character C#
我有一個包含此文本的字符串...
1. G66I11.J270.P5.C90.(+K2H1+)
2. G66I11.J90.P-5.(+K2H1+)
3. G66I215.4J270.P-55.Q-6.T2531(+K2H1+)
...
我需要提取字符“P”為 5 或 55 之后的值。
現在我使用 IndexOf 來獲取:
int indexP = 0;
int number;
if (lines.Contains("P-"))
{
indexP = lines.IndexOf("P-") + 1;
}
else if (lines.Contains("P") && !lines.Contains("P-"))
{
indexP = lines.IndexOf("P");
}
if (lines.Contains("Q"))
{
int indexQ = 0;
if (lines.Contains(".Q"))
{
indexQ = lines.IndexOf(".Q");
}
if (indexQ > indexP)
{
number = Int.Parse(lines.Substring(indexP + 1, indexQ - indexP - 1));
}
}
if (lines.Contains("C"))
{
int indexC = 0;
if (lines.Contains(".C"))
{
indexC = lines.IndexOf(".C");
}
if (indexC > indexP)
{
number = Int.Parse(lines.Substring(indexP + 1, indexC- indexP - 1));
}
}
...
我完全返回,但在“P”字符之后可以是任何字符。
因此,如果這樣做,它將是很長的代碼:(
我想找到一條更短的路。 你能告訴我怎么做嗎? 謝謝。
您可以使用正則Regex
和匹配表達式。 像這樣的東西,
// Example input
List<string> input = new List<string>();
input.Add("G66I11.J270.P5.C90.(+K2H1+)");
input.Add("G66I11.J90.P-5.(+K2H1+)");
input.Add("G66I215.4J270.P-55.Q-6.T2531(+K2H1+)");
input.Add("G66I11.J90.X-5.(+K2H1+)");
Regex match = new Regex(@"(?<=P)-*\d+(?=.)");
var values = input.Select(x => match.Match(x)?.Value).Where(x => !string.IsNullOrEmpty(x)).ToList();
// values =
Count = 3
[0]: "5"
[1]: "-5"
[2]: "-55"
Regex(@"(?<=P)-*\d+(?=.)");
-> 這從一開始就檢查P
.. 找到它之后,它需要 0 或更多-
.. 取數字 (\d+) 直到有.
.
唯一需要注意的是..它只選擇第一個匹配項。 如果您想要多個匹配項,請將match.Match
切換為match.Matches
方法,該方法會為您提供值列表。 您必須更新 Select 語句以返回所有值。
試試這個 - 假設你的 'lines' 是一個像這樣的多行字符串。
string lines = @"
1. G66I11.J270.P5.C90.(+K2H1+)
2. G66I11.J90.P-5.(+K2H1+)
3. G66I215.4J270.P-55.Q-6.T2531(+K2H1+)
";
Regex regex = new Regex(@"[^P]*P-?([^\.]+)\.");
var matches = regex.Matches(lines);
Console.WriteLine($"Count: {matches.Count}");
foreach (Match match in matches)
{
Console.WriteLine($"{match.Groups[1].Value}");
}
// Count: 3
// 5
// 5
// 55
對於單行:
Regex regex = new Regex(@"[^P]*P-?([^\.]+)\.");
string line = "1. G66I11.J270.P5.C90.(+K2H1+)";
var match = regex.Match(line);
Console.WriteLine($"{match.Groups[1].Value}");
// 5
您可以使用模式來匹配 P 后跟可選-
然后捕獲一組中的數字 0-9。
\bP-?([0-9]+\b
\bP-?
一個單詞邊界,匹配P
和可選-
([0-9]+)
捕獲組 1 中的 1 個或多個數字 0-9\b
防止部分單詞匹配的單詞邊界請參閱.NET 正則表達式演示(單擊表格選項卡)和C# 演示。
例如
string pattern = @"\bP-?([0-9]+)\b";
string s = @"1. G66I11.J270.P5.C90.(+K2H1+)
2. G66I11.J90.P-5.(+K2H1+)
3. G66I215.4J270.P-55.Q-6.T2531(+K2H1+)";
var numbers = Regex.Matches(s, pattern)
.Select(i => int.Parse(i.Groups[1].Value))
.ToArray();
Console.WriteLine("[{0}]", string.Join(", ", numbers));
Output
[5, 5, 55]
我按照賈瓦德的方式做到了
但它不匹配最后一個字符串有“P”的字符串,例如:G98X30.Y292.5I87.75J18.5P5
所以我在最終的正則表達式中添加了 *:
Regex match = new Regex(@"(?<=P)-*\d+(?=.)*");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.