c# - 正则表达式:匹配所有内容,直到最后一个空格
问题描述
我想将输入字符串的长度减少到最多 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 个字符的组,以空格结尾(或字符串结尾)
推荐阅读
- laravel - 如何在 laravel 5.6 中自动加载服务命名空间
- python - 无法加载静态文件
- ruby-on-rails - 在 Dockerized 应用程序上安装 Ruby Gem
- html - 如何在导航栏中将表单居中?
- java - 如何在java中使用字符串函数来解决这个问题
- php - Laravel 将动态子域重定向到文件夹
- python - 如何在同一行实时刷新控制台,Python
- python - Python 优化:使用向量技术查找 numpy 数组中每个矩阵的幂
- python - TypeError:“元组”对象不支持非元组对象上的项目分配
- spring-boot - Spring Boot 2 + Apache Shiro CGLIB 代理