Programming

괄호 (대괄호) 사이에있는 텍스트는 어떻게 추출합니까?

procodes 2020. 4. 25. 10:17
반응형

괄호 (대괄호) 사이에있는 텍스트는 어떻게 추출합니까?


문자열이 User name (sales)있고 대괄호 사이에 텍스트를 추출하고 싶습니다. 어떻게해야합니까?

하위 문자열을 의심하지만 닫는 대괄호까지 읽을 수있는 방법을 찾을 수 없습니다. 텍스트 길이는 다양합니다.


가장 간단한 방법은 정규식을 사용하는 것입니다.

Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value

(매우 웃긴) 의견에 대한 답변으로 다음과 같은 Regex가 있습니다.

\(             # Escaped parenthesis, means "starts with a '(' character"
    (          # Parentheses in a regex mean "put (capture) the stuff 
               #     in between into the Groups array" 
       [^)]    # Any character that is not a ')' character
       *       # Zero or more occurrences of the aforementioned "non ')' char"
    )          # Close the capturing group
\)             # "Ends with a ')' character"

정규 표현식을 피하고 싶다면 내가 생각할 수있는 가장 간단한 방법은 다음과 같습니다.

string input = "User name (sales)";
string output = input.Split('(', ')')[1];

한 쌍의 괄호 만 있다고 가정합니다.

string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);

이 기능을 사용하십시오 :

public string GetSubstringByString(string a, string b, string c)
    {
        return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
    }

그리고 사용법은 다음과 같습니다.

GetSubstringByString("(", ")", "User name (sales)")

출력은 다음과 같습니다.

sales

string input = "User name (sales)";

string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);

정규식이 여기에서 가장 좋은 도구 일 수 있습니다. 그들에 익숙하지 않다면 , 아주 작은 정규식 도구 인 Expresso 를 설치하는 것이 좋습니다 .

다음과 같은 것 :

Regex regex = new Regex("\\((?<TextInsideBrackets>\\w+)\\)");
string incomingValue = "Username (sales)";
string insideBrackets = null;
Match match = regex.Match(incomingValue);
if(match.Success)
{
    insideBrackets = match.Groups["TextInsideBrackets"].Value;
}

정규식? 나는 이것이 효과가 있다고 생각한다 ...

\(([a-z]+?)\)

using System;
using System.Text.RegularExpressions;

private IEnumerable<string> GetSubStrings(string input, string start, string end)
{
    Regex r = new Regex(Regex.Escape(start) +`"(.*?)"`  + Regex.Escape(end));
    MatchCollection matches = r.Matches(input);
    foreach (Match match in matches)
    yield return match.Groups[1].Value;
}

정규식을 사용하십시오.

string test = "(test)"; 
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);

input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);

regex내가 생각 하는 방법은 우수하지만 겸손을 사용하고 싶다면substring

string input= "my name is (Jayne C)";
int start = input.IndexOf("(");
int stop = input.IndexOf(")");
string output = input.Substring(start+1, stop - start - 1);

또는

string input = "my name is (Jayne C)";
string output  = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1);

int start = input.IndexOf("(") + 1;
int length = input.IndexOf(")") - start;
output = input.Substring(start, length);

정규 표현식이 매우 유용하지만 작성하기가 매우 어렵다는 것을 알게되었습니다. 그래서, 나는 약간의 연구를했고 그것들을 아주 쉽게 쓰는 도구찾았 습니다.

구문을 이해하기 어렵 기 때문에 부끄러워하지 마십시오. 그들은 매우 강력 할 수 있습니다.


다음은 정규식 사용을 피하는 범용 판독 가능 함수입니다.

// Returns the text between 'start' and 'end'.
string ExtractBetween(string text, string start, string end)
{
  int iStart = text.IndexOf(start);
  iStart = (iStart == -1) ? 0 : iStart + start.Length;
  int iEnd = text.LastIndexOf(end);
  if(iEnd == -1)
  {
    iEnd = text.Length;
  }
  int len = iEnd - iStart;

  return text.Substring(iStart, len);
}

특정 예제에서 호출하려면 다음을 수행하십시오.

string result = ExtractBetween("User name (sales)", "(", ")");

매우 유사한 구현에 대한 솔루션을 찾고있는 동안이 문제를 겪었습니다.

다음은 실제 코드의 스 니펫입니다. 첫 번째 문자 (인덱스 0)에서 하위 문자열을 시작합니다.

 string separator = "\n";     //line terminator

 string output;
 string input= "HowAreYou?\nLets go there!";

 output = input.Substring(0, input.IndexOf(separator)); 

이 코드는 String extension method 로 포장 된 대부분의 솔루션보다 빠르며 ( 재귀하지는 않지만) 재귀 중첩을 지원하지 않습니다.

public static string GetNestedString(this string str, char start, char end)
{
    int s = -1;
    int i = -1;
    while (++i < str.Length)
        if (str[i] == start)
        {
            s = i;
            break;
        }
    int e = -1;
    while(++i < str.Length)
        if (str[i] == end)
        {
            e = i;
            break;
        }
    if (e > s)
        return str.Substring(s + 1, e - s - 1);
    return null;
}

이것은 조금 길고 느리지 만 재귀 중첩을보다 잘 처리합니다.

public static string GetNestedString(this string str, char start, char end)
{
    int s = -1;
    int i = -1;
    while (++i < str.Length)
        if (str[i] == start)
        {
            s = i;
            break;
        }
    int e = -1;
    int depth = 0;
    while (++i < str.Length)
        if (str[i] == end)
        {
            e = i;
            if (depth == 0)
                break;
            else
                --depth;
        }
        else if (str[i] == start)
            ++depth;
    if (e > s)
        return str.Substring(s + 1, e - s - 1);
    return null;
}

참고 URL : https://stackoverflow.com/questions/378415/how-do-i-extract-text-that-lies-between-parentheses-round-brackets

반응형