C # Best way to break a long string

This question is not related to:

Best way to break long lines in C # source code

As for the source, it is about processing long outputs. If someone enters:

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW WW W W W W W W W W W W W W W W W

As a comment, it breaks the container and makes the whole page very wide. Is there any clever regex that can say to determine the maximum word length of 20 characters and then force the whitespace?

Thanks for any help!

+4
source share
3 answers

There is probably no need to involve regular expressions in something so simple. Take this extension method:

public static string Abbreviate(this string text, int length) { if (text.Length <= length) { return text; } char[] delimiters = new char[] { ' ', '.', ',', ':', ';' }; int index = text.LastIndexOfAny(delimiters, length - 3); if (index > (length / 2)) { return text.Substring(0, index) + "..."; } else { return text.Substring(0, length - 3) + "..."; } } 

If the string is short enough, it is returned as-is. Otherwise, if the word boundary is in the second half of the line, it is “gracefully” cut off at that point. If not, it cuts off the hard path under the desired length.

If the line is disabled at all, an ellipsis ("...") is added to it.

If you expect the string to contain constructors based on an unnatural language (such as a URL), you need to tweak it to ensure good behavior in all circumstances. In this case, working with a regular expression might be better.

+5
source

You can try using a regex that uses a positive forecast ahead:

 string outputStr = Regex.Replace(inputStr, @"([\S]{20}(?=\S+))", "$1\n"); 

This should “insert” a line break in all words longer than 20 characters.

+3
source

Yes you can use this one regex

 string pattern = @"^([\w]{1,20})$"; 

this regular expression allows you to enter a maximum of 20 characters

 string strRegex = @"^([\w]{1,20})$"; string strTargetString = @"asdfasfasfasdffffff"; if(Regex.IsMatch(strTargetString, strRegex)) { //do something } 

If you only need a length limit, you should use this regex

 ^(.{1,20})$ 

because \ w matches only an alphanumeric character and an underscore

+2
source

All Articles