我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?

我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。


当前回答

下面是一个通用的可读函数,避免使用regex:

// 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)", "(", ")");

其他回答

下面是一个通用的可读函数,避免使用regex:

// 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)", "(", ")");

我发现正则表达式非常有用,但很难写。所以,我做了一些研究,发现这个工具可以让写它们变得如此简单。

不要因为语法很难理解而回避它们。它们可以如此强大。

使用正则表达式:

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

我认为regex方法更好,但如果你想使用卑微的子字符串

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

or

string input = "my name is (Jayne C)";
string output  = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1);
 var input = "12(34)1(12)(14)234";
 var output = "";
 for (int i = 0; i < input.Length; i++)
 {
     if (input[i] == '(')
     {
         var start = i + 1;
         var end = input.IndexOf(')', i + 1);
         output += input.Substring(start, end - start) + ",";
     }
 }

 if (output.Length > 0) // remove last comma
  output = output.Remove(output.Length - 1);

输出:“34,12,14”