Reputation: 15559
I want to reduce the length of my input string to max 20 characters, but I don't want't to break the string in the middle of a word.
// show me 20 char: 12345678901234567890
string inputString = "This is an example user input which has to be shorten at a white space";
if (inputString.length > 20)
{
shortenString = inputString.SubString(0, 21); // <-- "This is an example us"
// I need a regex to match everything until the last white space
// final output: "This is an example"
}
Upvotes: 1
Views: 547
Reputation: 15559
I used the RegEx from @Ced answer, this is the final extension method:
public static string ShortenStringAtWhiteSpaceIfTooLong(this string str, int maxLen)
{
if (str.Length <= maxLen)
{
return str;
}
string pattern = @"^(.{0," + maxLen.ToString() + @"})\s"; // <-- @"^(.{0,20})\s"
Regex regEx = new Regex(pattern);
var matches = regEx.Matches(str);
if (matches.Count > 0)
{
return matches[0].Value.Trim();
}
else
{
return str.Substring(0, maxLen).Trim();
}
}
Upvotes: 1
Reputation: 1207
(.{0,20})(\s|$)
this regex will capture groups up to 20 characters, ending in whitespace (or end of string)
Upvotes: 2