簡體   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