我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
当前回答
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;
}
其他回答
也许是正则表达式?我认为这行得通……
\(([a-z]+?)\)
我发现正则表达式非常有用,但很难写。所以,我做了一些研究,发现这个工具可以让写它们变得如此简单。
不要因为语法很难理解而回避它们。它们可以如此强大。
input.Remove(input.IndexOf(')')).Substring(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;
}
我在寻找一个非常相似的实现的解决方案时遇到了这个问题。
下面是我的实际代码片段。从第一个字符(索引0)开始子字符串。
string separator = "\n"; //line terminator
string output;
string input= "HowAreYou?\nLets go there!";
output = input.Substring(0, input.IndexOf(separator));