c # Как получить подстроку с более чем одним и тем же символом - PullRequest
0 голосов
/ 25 сентября 2019

У меня есть следующая строка с переменной s:

Room: 501, User: John, Model: XPR500 Serial: JK0192, Condition: Good

Я хочу извлечь модель, XPR500 и серийный номер, JK0192

Мне удалось получить модель со следующим кодом:

                int pFrom = s.IndexOf("Model: ") + "Model: ".Length;
                int pTo = s.LastIndexOf(" Serial:");

                String model = s.Substring(pFrom, pTo - pFrom);

Но у меня возникли трудности с получением серийного значения.Я попытался этот код:

                int pFromt = s.IndexOf("Serial: ") + "Serial: ".Length;
                int pToT = s.LastIndexOf(", ");

                string serial = s.Substring(pFromt, pToT - pFromt);

, но он возвращает

JK0192,Condition: Good

У меня проблемы с получением, чтобы получить все из Serial: и следующей запятой.

Кто-нибудь может увидеть, где я иду не так?

Ответы [ 2 ]

1 голос
/ 25 сентября 2019

Вы можете попробовать использовать простое регулярное выражение:

@"Model\:\s([\w\d]*).*Serial\:\s([\w\d]*).*"

Вот полный пример:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"Model\:\s([\w\d]*).*Serial\:\s([\w\d]*).*";
        string input = @"Room: 501, User: John, Model: XPR500   Serial: JK0192, Condition: Good";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

Надеюсь, это поможет

0 голосов
/ 25 сентября 2019

Вы можете использовать массив разделителей строк.Я бы использовал названия в качестве разделителей.Я не буду использовать запятую, потому что:

  1. Запятая не всегда является разделителем
  2. Вам все равно нужно будет удалить заголовки

Вот кодты можешь попробовать.Он использует String.Split вместо того, чтобы искать только строки вручную и анализировать подстроки

static void Main(string[] args)
{
    var s = "Room: 501, User: John, Model: XPR500   Serial: JK0192, Condition: Good";
    s = s.Replace(",", ""); // first, remove all the commas
    var delimiters = new string[] { "Room:", "User:", "Model:", "Serial:", "Condition:" };
    // use a function which doesn't assume the order or inclusion of all the delimiters
    model = getValue(s, delimiters, "Model:");
    serial = getValue(s, delimiters, "Serial:");
    Console.WriteLine($"Model = '{model}'");
    Console.WriteLine($"Serial = '{serial}'");
    Console.ReadLine();
}

private static string getValue(string s, string[] delimiters, string delimiter)
{
    // find the index of the beginning of the rest of the string after your sought title
    var index = s.IndexOf(delimiter) + delimiter.Length;
    // split the rest of the string by all the delimiters, take the first item
    return s.Substring(index).Split(delimiters, StringSplitOptions.RemoveEmptyEntries).First().Trim();
}
...