code

하위 문자열 가져오기 - 특정 문자 앞의 모든 항목

starcafe 2023. 8. 6. 10:15
반응형

하위 문자열 가져오기 - 특정 문자 앞의 모든 항목

저는 문자열의 - 문자 앞에 있는 모든 것을 가져올 수 있는 가장 좋은 방법을 찾고 있습니다.다음은 몇 가지 예제 문자열입니다.이전 문자열의 길이 - 다양하며 임의의 길이일 수 있습니다.

223232-1.jpg
443-2.jpg
34443553-5.jpg

시작 인덱스 0에서 시작 직전까지의 값이 필요합니다. 그래서 서브스트링은 223232, 443, 34443553이 됩니다.

.Net Fiddle 예제

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
        Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
        Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());

        Console.ReadKey();
    }
}

static class Helper
{
    public static string GetUntilOrEmpty(this string text, string stopAt = "-")
    {
        if (!String.IsNullOrWhiteSpace(text))
        {
            int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);

            if (charLocation > 0)
            {
                return text.Substring(0, charLocation);
            }
        }

        return String.Empty;
    }
}

결과:

223232
443
34443553
344

34

분할 함수를 사용합니다.

static void Main(string[] args)
{
    string s = "223232-1.jpg";
    Console.WriteLine(s.Split('-')[0]);
    s = "443-2.jpg";
    Console.WriteLine(s.Split('-')[0]);
    s = "34443553-5.jpg";
    Console.WriteLine(s.Split('-')[0]);

Console.ReadKey();
}

문자열에 다음이 없는 경우-그러면 당신은 모든 끈을 얻게 될 것입니다.

String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
    return str.Substring(0, index)
}

이 스레드가 시작된 이후로 상황이 조금 나아졌습니다.

이제, 당신은 사용할 수 있습니다.

string.Concat(s.TakeWhile((c) => c != '-'));

한 가지 방법은 다음을 사용하는 것은String.Substring와 함께String.IndexOf:

int index = str.IndexOf('-');
string sub;
if (index >= 0)
{
    sub = str.Substring(0, index);
}
else
{
    sub = ... // handle strings without the dash
}

위치 0에서 시작하여 대시를 제외한 모든 텍스트를 반환합니다.

약간 수정되고 새로워진 Fredou의 C# »8용 솔루션

/// <summary>
/// Get substring until first occurrence of given character has been found. Returns the whole string if character has not been found.
/// </summary>
public static string GetUntil(this string that, char @char)
{
    return that[..(IndexOf() == -1 ? that.Length : IndexOf())];
    int IndexOf() => that.IndexOf(@char);
}

테스트:

[TestCase("", ' ', ExpectedResult = "")]
[TestCase("a", 'a', ExpectedResult = "")]
[TestCase("a", ' ', ExpectedResult = "a")]
[TestCase(" ", ' ', ExpectedResult = "")]
[TestCase("/", '/', ExpectedResult = "")]
[TestCase("223232-1.jpg", '-', ExpectedResult = "223232")]
[TestCase("443-2.jpg", '-', ExpectedResult = "443")]
[TestCase("34443553-5.jpg", '-', ExpectedResult = "34443553")]
[TestCase("34443553-5-6.jpg", '-', ExpectedResult = "34443553")]
public string GetUntil(string input, char until) => input.GetUntil(until);

LIN 키웨이

String.Concat("223232-1.jpg").TakeWhile (c = > c!= '-')

(그러나 null을 테스트해야 합니다;)

BrainCore의 답변을 기반으로 합니다.

    int index = 0;   
    str = "223232-1.jpg";

    //Assuming we trust str isn't null 
    if (str.Contains('-') == "true")
    {
      int index = str.IndexOf('-');
    }

    if(index > 0) {
        return str.Substring(0, index);
    }
    else {
       return str;
    }

이 경우 정규식을 사용할 수 있지만 입력 문자열이 정규식과 일치하지 않을 때는 추가 예외를 피하는 것이 좋습니다.

먼저 정규식 패턴으로 탈출하는 데 따른 추가적인 두통을 피하기 위해 기능을 사용할 수 있습니다.

String reStrEnding = Regex.Escape("-");

"-"와 동일하기 때문에, 저는 이것이 아무것도 하지 않는다는 것을 압니다.Regex.Escape("=") == "="하지만 예를 들어 캐릭터가 다른 것이라면 그것은 차이를 만들 것입니다.@"\".

그런 다음 문자열 구걸에서 문자열 끝까지 일치하거나, 또는 끝을 찾을 수 없는 경우에는 아무 것도 일치하지 않아야 합니다. (빈 문자열)

Regex re = new Regex("^(.*?)" + reStrEnding);

애플리케이션이 성능에 중요한 경우(그렇지 않은 경우에는 새 Regex에 대해 별도의 줄을 사용) 모든 것을 한 줄로 구성할 수 있습니다.

마지막으로 문자열과 일치하고 일치하는 패턴을 추출합니다.

String matched = re.Match(str).Groups[1].ToString();

그런 다음 다른 답처럼 별도의 함수를 쓰거나 인라인 람다 함수를 쓸 수 있습니다.인라인 람다 함수(기본 매개 변수 허용 안 함) 또는 별도 함수 호출의 두 가지 표기법을 사용하여 작성했습니다.

using System;
using System.Text.RegularExpressions;

static class Helper
{
    public static string GetUntilOrEmpty(this string text, string stopAt = "-")
    {
        return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Regex re = new Regex("^(.*?)-");
        Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); };

        Console.WriteLine(untilSlash("223232-1.jpg"));
        Console.WriteLine(untilSlash("443-2.jpg"));
        Console.WriteLine(untilSlash("34443553-5.jpg"));
        Console.WriteLine(untilSlash("noEnding(will result in empty string)"));
        Console.WriteLine(untilSlash(""));
        // Throws exception: Console.WriteLine(untilSlash(null));

        Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
    }
}

Btw - 정규식 패턴 변경"^(.*?)(-|$)"다음 시간까지 둘 중 하나를 픽업할 수 있습니다."-"패턴 또는 패턴을 찾을 수 없는 경우 문자열이 끝날 때까지 모든 항목을 선택합니다.

언급URL : https://stackoverflow.com/questions/1857513/get-substring-everything-before-certain-char

반응형