Ho una stringa User name (sales)
e desidero estrarre il testo tra parentesi, come farei?
Ho il sospetto che la sottostringa non riesca a capire come leggere fino alla parentesi di chiusura, la lunghezza del testo varierà.
Ho una stringa User name (sales)
e desidero estrarre il testo tra parentesi, come farei?
Ho il sospetto che la sottostringa non riesca a capire come leggere fino alla parentesi di chiusura, la lunghezza del testo varierà.
Risposte:
Se desideri stare lontano dalle espressioni regolari, il modo più semplice a cui riesco a pensare è:
string input = "User name (sales)";
string output = input.Split('(', ')')[1];
var input = "(fdw) User name (sales) safdsdf (again?)"; var output = input.Split('(', ')').Where((item, index) => index % 2 != 0).ToList();
sales
anche dalle stringhe di input contenenti )sales(
, (sales(
ecc.
Un modo molto semplice per farlo è usare espressioni regolari:
Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value
Come risposta al commento (molto divertente), ecco lo stesso Regex con alcune spiegazioni:
\( # 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"
var filterRegex = new Regex(Regex.Escape("(") + "([^()]*)" + Regex.Escape(")"));
Supponendo di avere solo una coppia di parentesi.
string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
int end = s.IndexOf(")", start);
. Ho messo in coda una modifica ...
Usa questa funzione:
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));
}
e qui è l'uso:
GetSubstringByString("(", ")", "User name (sales)")
e l'output sarebbe:
sales
Le espressioni regolari potrebbero essere lo strumento migliore qui. Se non hai familiarità con loro, ti consiglio di installare Expresso - un ottimo strumento regex.
Qualcosa di simile a:
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);
input = "User name (sales(1))
potresti voler usare input.LastIndexOf(')')
quale funzionerà se ci sono parentesi interne o meno.
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;
}
int start = input.IndexOf("(") + 1;
int length = input.IndexOf(")") - start;
output = input.Substring(start, length);
Il regex
metodo è superiore credo, ma se si voleva utilizzare gli umilisubstring
string input= "my name is (Jayne C)";
int start = input.IndexOf("(");
int stop = input.IndexOf(")");
string output = input.Substring(start+1, stop - start - 1);
o
string input = "my name is (Jayne C)";
string output = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1);
Ecco una funzione leggibile per uso generale che evita l'uso di 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);
}
Per chiamarlo nel tuo esempio particolare puoi fare:
string result = ExtractBetween("User name (sales)", "(", ")");
Sto scoprendo che le espressioni regolari sono estremamente utili ma molto difficili da scrivere. Quindi, ho fatto qualche ricerca e ho trovato questo strumento che semplifica la scrittura.
Non esitare da loro perché la sintassi è difficile da capire. Possono essere così potenti.
Mi sono imbattuto in questo mentre cercavo una soluzione per un'implementazione molto simile.
Ecco uno snippet dal mio codice attuale. Inizia la sottostringa dal primo carattere (indice 0).
string separator = "\n"; //line terminator
string output;
string input= "HowAreYou?\nLets go there!";
output = input.Substring(0, input.IndexOf(separator));
Questo codice è più veloce della maggior parte delle soluzioni qui (se non tutte), compresso come metodo di estensione String , non supporta l'annidamento ricorsivo:
public static string GetNestedString(this string str, char start, char end)
{
int s = -1;
int i = -1;
while (++i < str.Length)
if (str[i] == start)
{
s = i;
break;
}
int e = -1;
while(++i < str.Length)
if (str[i] == end)
{
e = i;
break;
}
if (e > s)
return str.Substring(s + 1, e - s - 1);
return null;
}
Questo è un po 'più lungo e più lento, ma gestisce più facilmente l'annidamento ricorsivo:
public static string GetNestedString(this string str, char start, char end)
{
int s = -1;
int i = -1;
while (++i < str.Length)
if (str[i] == start)
{
s = i;
break;
}
int e = -1;
int depth = 0;
while (++i < str.Length)
if (str[i] == end)
{
e = i;
if (depth == 0)
break;
else
--depth;
}
else if (str[i] == start)
++depth;
if (e > s)
return str.Substring(s + 1, e - s - 1);
return null;
}