I will have a list of string in the following format: PERSON NAME ( LOGIN ), / p>
So, I would need to get only what would be within the parentheses, ie zackson.morgan .
How to do this?
I will have a list of string in the following format: PERSON NAME ( LOGIN ), / p>
So, I would need to get only what would be within the parentheses, ie zackson.morgan .
How to do this?
A simple way to do this is to locate the position of the two parentheses and get the inner part, like this:
using static System.Console;
public class Program {
public static void Main() {
var texto = "ZACKSON MOREIRA MORGAN (zackson.morgan)";
WriteLine(pegaTexto(texto));
texto = "ZACKSON MOREIRA MORGAN (zackson.morgan";
WriteLine(pegaTexto(texto));
texto = "ZACKSON MOREIRA MORGAN (";
WriteLine(pegaTexto(texto));
}
public static string pegaTexto(string texto) {
texto += ")";
texto = texto.Substring(texto.IndexOf("(") + 1);
return texto.Substring(0, texto.IndexOf(")"));
}
}
See running dotNetFiddle .
While the @bigown solution largely solves the issue, there is the regular expression version to solve the problem:
private static Regex regex = new Regex("^.*\((?<login>.*)\)$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
public static void Main()
{
WriteLine(GetLogin("ZACKSON MOREIRA MORGAN (zackson.morgan)"));
WriteLine(GetLogin("ZACKSON MOREIRA MORGAN (zackson.morgan"));
WriteLine(GetLogin("ZACKSON MOREIRA MORGAN )"));
WriteLine(GetLogin("ZACKSON MOREIRA MORGAN ("));
WriteLine(GetLogin("ZACKSON MOREIRA MORGAN"));
}
private static string GetLogin(string input)
{
var res = regex.Match(input);
if(res.Success)
return res.Groups["login"].Value;
else
return "No matches found";
}
In this case, the (?<input>.*)
syntax captures all characters between parentheses (defined by \(
and \)
).
See working on dotNetFiddle .