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

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

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



답변

정규식을 피하고 싶다면 가장 간단한 방법은 다음과 같습니다.

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

답변

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

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 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

답변

정규식이 여기에서 가장 좋은 도구 일 수 있습니다. 그들에 익숙하지 않다면 , 아주 작은 정규식 도구 인 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;
}

답변

string input = "User name (sales)";

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

답변

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

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