You can use regular expressions for this purpose, but it s good to avoid extra exceptions when input string mismatches against regular expression.
First to avoid extra headache of escaping to regex pattern - we could just use function for that purpose:
String reStrEnding = Regex.Escape("-");
I know that this does not do anything - as "-" is the same as Regex.Escape("=") == "="
, but it will make difference for example if character is @""
.
Then we need to match from begging of the string to string ending, or alternately if ending is not found - then match nothing. (Empty string)
Regex re = new Regex("^(.*?)" + reStrEnding);
If your application is performance critical - then separate line for new Regex, if not - you can have everything in one line.
And finally match against string and extract matched pattern:
String matched = re.Match(str).Groups[1].ToString();
And after that you can either write separate function, like it was done in another answer, or write inline lambda function. I ve wrote now using both notations - inline lambda function (does not allow default parameter) or 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(""));
// Throws exception: Console.WriteLine(untilSlash(null));
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
}
}
Btw - changing regex pattern to "^(.*?)(-|$)"
will allow to pick up either until "-"
pattern or if pattern was not found - pick up everything until end of string.