开发者

c# Best way to break up a long string

开发者 https://www.devze.com 2023-02-28 01:56 出处:网络
This question is not related to: B开发者_StackOverflow中文版est way to break long strings in C# source code

This question is not related to:

B开发者_StackOverflow中文版est way to break long strings in C# source code

Which is about source, this is about processing long outputs. If someone enters:

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW

As a comment, it breaks the container and makes the entire page really wide. Is there any clever regexp that can say, define a maximum word length of 20 chars and then force a whitespace character?

Thanks for any help!


There's probably no need to involve regexes in something this 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's returned as-is. Otherwise, if a "word boundary" is found in the second half of the string, it's "gracefully" cut off at that point. If not, it's cut off the hard way at just under the desired length.

If the string is cut off at all, an ellipsis ("...") is appended to it.

If you expect the string to contain non-natural-language constructs (such as URLs) you 'd need to tweak this to ensure nice behavior in all circumstances. In that case working with a regex might be better.


You could try using a regular expression that uses a positive look-ahead like this:

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

This should "insert" a line break into all words that are longer than 20 characters.


Yes you can use this one regex

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

this regex allow to enter not more than 20 characters

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

if(Regex.IsMatch(strTargetString, strRegex))
{
    //do something
}

If you need only lenght constraint you should use this regex

^(.{1,20})$

because the \w is match only alphanumeric and underscore symbol

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号