繁体   English   中英

正则表达式:匹配所有内容,直到最后一个空格

[英]Regex: Match everything until the last white space

我想将输入字符串的长度减少到最多 20 个字符,但我不想在单词中间破坏字符串。

// 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"
}

(.{0,20})(\s|$)此正则表达式将捕获最多 20 个字符的组,以空格结尾(或字符串结尾)

我使用了来自@Ced 答案的正则表达式,这是最终的扩展方法:

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM