我有一个字符串User name (sales),我想在括号之间提取文本,我该怎么做?
我怀疑子字符串,但我无法弄清楚如何阅读,直到结束括号,文本的长度会有所不同.
Dia*_*tis 425
一个非常简单的方法是使用正则表达式:
Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value
Run Code Online (Sandbox Code Playgroud)
作为对(非常有趣的)评论的回应,这里有相同的正则表达式,并有一些解释:
\( # 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"
Run Code Online (Sandbox Code Playgroud)
Jel*_*Ama 421
如果你想远离正则表达式,我能想到的最简单的方法是:
string input = "User name (sales)";
string output = input.Split('(', ')')[1];
Run Code Online (Sandbox Code Playgroud)
Ros*_*ard 91
假设你只有一对括号.
string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
Run Code Online (Sandbox Code Playgroud)
art*_*ker 24
使用此功能:
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));
}
Run Code Online (Sandbox Code Playgroud)
这是用法:
GetSubstringByString("(", ")", "User name (sales)")
Run Code Online (Sandbox Code Playgroud)
输出将是:
sales
Run Code Online (Sandbox Code Playgroud)
Jen*_*fer 14
正则表达式可能是这里最好的工具.如果你不熟悉它们,我建议你安装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;
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*len 14
string input = "User name (sales)";
string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
Run Code Online (Sandbox Code Playgroud)
小智 7
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;
}
Run Code Online (Sandbox Code Playgroud)
int start = input.IndexOf("(") + 1;
int length = input.IndexOf(")") - start;
output = input.Substring(start, length);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
310757 次 |
| 最近记录: |