How to remove extra returns and spaces in a string by regex?(如何通过正则表达式删除字符串中的额外返回和空格?)
问题描述
我将HTML代码转换为纯文本.但是有很多额外的返回和空格.如何删除它们?
I convert a HTML code to plain text.But there are many extra returns and spaces.How to remove them?
推荐答案
我假设你想要
- 找到两个或多个连续的空格并将它们替换为一个空格,然后
- 找到两个或多个连续的换行符并将它们替换为一个换行符.
如果是正确的,那么你可以使用
If that's correct, then you could use
resultString = Regex.Replace(subjectString, @"( |
?
)1+", "$1");
这会保持空白的原始类型"不变,并正确保留 Windows 行尾.如果您还想将多个选项卡压缩"为一个,请使用
This keeps the original "type" of whitespace intact and also preserves Windows line endings correctly. If you also want to "condense" multiple tabs into one, use
resultString = Regex.Replace(subjectString, @"( | |
?
)1+", "$1");
要将一串换行符和空格(任意数量)压缩成一个换行符,请使用
To condense a string of newlines and spaces (any number of each) into a single newline, use
resultString = Regex.Replace(subjectString, @"(?:(?:
?
)+ +){2,}", @"
");
这篇关于如何通过正则表达式删除字符串中的额外返回和空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过正则表达式删除字符串中的额外返回和空格?


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01