我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
当前回答
input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);
其他回答
如果你想远离正则表达式,我能想到的最简单的方法是:
string input = "User name (sales)";
string output = input.Split('(', ')')[1];
使用正则表达式:
string test = "(test)";
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);
我在寻找一个非常相似的实现的解决方案时遇到了这个问题。
下面是我的实际代码片段。从第一个字符(索引0)开始子字符串。
string separator = "\n"; //line terminator
string output;
string input= "HowAreYou?\nLets go there!";
output = input.Substring(0, input.IndexOf(separator));
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;
}
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”