正则表达式匹配空行 [英] Regex match empty lines
问题描述
目前我有一个正则表达式,它将采用一组给定的换行符并将它们压缩.我需要解决的一个挑战是修改这个正则表达式(\n{2,}
) 以便在搜索多个换行符时仍然会忽略空格和制表符.
https://regex101.com/r/dEhyN3/2 显示效果很好我所指的例子.有一行只包含一个空格,导致最终结果中有太多新行.
Brief
此答案可确保保留行首的空格(如果它包含除空格字符以外的其他内容).
<小时>代码
(?:\h*\n){2,}
注意:某些正则表达式引擎不允许使用 \h
,因此必须将其替换为 [\t\p{Zs}]
,如果不支持 Unicode 字符类,则为每个字符的简单列表,例如 [\t ]
或 [^\S\n]
.>
其他方法:
(?:\n(?:[^\S\n]*(?=\n))?){2,}(?:\n(?:\s*(?=\n))?){2,}\h*\n(?:\h*\n)+
<小时>
结果
输入
**语言**- 添加了四种语言:意大利语、葡萄牙语(巴西)、西班牙语(墨西哥)和中文(繁体)**Bug修复**- 修正了坐在带边车的摩托车后面的乘客的相机抖动- 修正了坐在带边车的摩托车后面的乘客的相机抖动
输出
**语言**- 添加了四种语言:意大利语、葡萄牙语(巴西)、西班牙语(墨西哥)和中文(繁体)**Bug修复**- 修正了坐在带边车的摩托车后面的乘客的相机抖动- 修正了坐在带边车的摩托车后面的乘客的相机抖动
<小时>
说明
(?:\h*\n){2,}
匹配任意数量的水平空白字符后跟换行符,两次或多次
其他方法
只是为了解释至少一种其他方法(并保留我原来的答案)
(?:\n(?:[^\S\n]*(?=\n))?){2,}
匹配以下两次或多次\n
匹配换行符(?:[^\S\n]*(?=\n))?
匹配以下零次或一次[^\S\n]*
匹配除\n
之外的任何空白字符任意次数(?=\n)
正向前瞻确保后面是换行\n
Currently I have a regex that will take a given set of newlines and condense them. A challenge I need to solve for is to modify this regex (\n{2,}
) so that it still will ignore spaces and tabs when searching for multiple newline characters.
https://regex101.com/r/dEhyN3/2 shows a good working example of what I'm referring to. There's a line that only contains a space which leads to too many new lines in the end result.
Brief
This answer ensures whitespace at the start of a line is kept (if it contains something other than a whitespace character).
Code
(?:\h*\n){2,}
Note: Some regex engines don't allow \h
, so this will have to be replaced with [\t\p{Zs}]
, and if Unicode character classes are not supported, a simple list of each character such as [\t ]
or [^\S\n]
.
Other methods:
(?:\n(?:[^\S\n]*(?=\n))?){2,}
(?:\n(?:\s*(?=\n))?){2,}
\h*\n(?:\h*\n)+
Results
Input
**Language**
- Added four languages: Italian, Portuguese (Brazil), Spanish (Mexico) and Chinese (Traditional)
**Bug fixes**
- Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
- Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
Output
**Language**
- Added four languages: Italian, Portuguese (Brazil), Spanish (Mexico) and Chinese (Traditional)
**Bug fixes**
- Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
- Fixed camera jittering for passenger sitting on the back of a motorcycle with sidecar
Explanation
(?:\h*\n){2,}
Match any number of horizontal whitespace character followed by a line-feed, two or more times
Other methods
Just to explain at least one of the other methods (and keep my original answer)
(?:\n(?:[^\S\n]*(?=\n))?){2,}
Matches the following two or more times\n
Match a line-feed character(?:[^\S\n]*(?=\n))?
Match the following zero or one time[^\S\n]*
Match any whitespace character except\n
any number of times(?=\n)
Positive lookahead ensuring what follows is a line-feed\n
这篇关于正则表达式匹配空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!