首页 > 解决方案 > 正则表达式:匹配所有内容,直到最后一个空格

问题描述

我想将输入字符串的长度减少到最多 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"
}

标签: c#regex

解决方案


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


推荐阅读