You can use regular expressions for this purpose, but it is good to avoid additional exceptions when the input string does not match the regular expression.
Firstly, in order to avoid additional headaches when switching to the regular expression pattern, we could simply use the function for this purpose:
String reStrEnding = Regex.Escape("-");
I know that this does nothing - since "-" is the same as Regex.Escape("=") == "=" , but it will make a difference, for example, if the @"\" character .
Then we need to match from the beginning of the line to the end of the line or, alternatively, if the end is not found, then nothing is found. (Blank line)
Regex re = new Regex("^(.*?)" + reStrEnding);
If your application is performance critical, then select a new line for the new Regex, if not, everything can be on one line.
Finally, match the string and extract the appropriate pattern:
String matched = re.Match(str).Groups[1].ToString();
And after that you can write a separate function, as it was done in another answer, or write a built-in lambda function. I wrote now using both notations - the built-in lambda function (does not allow the default parameter) or a separate function call.
using System; using System.Text.RegularExpressions; static class Helper { public static string GetUntilOrEmpty(this string text, string stopAt = "-") { return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value; } } class Program { static void Main(string[] args) { Regex re = new Regex("^(.*?)-"); Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); }; Console.WriteLine(untilSlash("223232-1.jpg")); Console.WriteLine(untilSlash("443-2.jpg")); Console.WriteLine(untilSlash("34443553-5.jpg")); Console.WriteLine(untilSlash("noEnding(will result in empty string)")); Console.WriteLine(untilSlash(""));
By the way, changing the regular expression pattern to "^(.*?)(-|$)" will allow you to select the pattern before "-" or, if the pattern was not found, collect everything to the end of the line.