C # How to get specific text located inside a string?

Does anyone know how to get a short sentence from the main line? Is regular expression required?

I am trying to get the text "Thu Dec 9 05:12:42 2010", which is the time from the main line "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)", which is after "Time" "and before" (UTC ) ".

I am also new to C #, so sorry for the simple question.

Can someone consult or show some C # methods that can be used to extract text? Thank you

+2
source share
7 answers

You can use regex:

Match match = Regex.Match(text, @"Time (.*?)\(UTC\)");

match.Groups[1].Value.

+3

System.String.Substring System.String.Length.

var logTime = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)";
logTime = logTime.Substring("LastWrite Time ".Length);
logTime = logTime.Substring(0, logTime.Length - " (UTC)".Length);

, .

+1

(regex), . , . , Regex, #.

, , String. , .

, . , /, ( ). Substring(...). . .

+1

, . :

String value = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)";

String newValue = value.Replace("LastWrite Time", "").Replace("(UTC)", "").Trim();

Regular Expressions.

0

, , SubString() . :

String str = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)"; str.substring(15,23);

Thu Dec 9 05:12:42 2010 .

0

- , , .

- IndexOf Substring . . , , , .

- , .

- , , , , . - .

0
source

This is a fairly common problem, so you should extend the string class with the flexible Between method. First you need to define an extension class:

public static class StringExtensions
{
    /// <summary>
    /// Returnes a substring located between a leading substring (head) and following substring(tail).
    /// Return null if head or tail are not part of this string.  
    /// </summary>
    /// <param name="mainString"></param>
    /// <param name="head">leading substring</param>
    /// <param name="tail">following substring</param>
    /// <returns>ubstring located between head and tail</returns>
    public static String Between(this string mainString, string head, string tail)
    {
        int HeadPosition;
        int TailPosition;
        int ResultPosition;
        int ResultLenght;
        //test if mainstring contains head and tail
        if (!mainString.Contains(head) && mainString.Contains(tail))
        {
            return null;
        }
        HeadPosition = mainString.IndexOf(head);
        TailPosition = mainString.IndexOf(tail);
        ResultPosition = HeadPosition + head.Length;
        ResultLenght = TailPosition - ResultPosition;

        return mainString.Substring(ResultPosition, ResultLenght);
    }
}

Then all you have to do is call a new method for any line.

var logTime = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)";
logTime = logTime.Between("Time","(UTC)").Trim();

Please note that Between will only be available if you use the namespace that you specified StringExtensions in.

0
source

Source: https://habr.com/ru/post/1779966/


All Articles