H S*_*H S 5 python regex notepad++
我重新格式化使用记事本++ Python脚本,但一些线不通过4(或8,12,16,等等)的空间缩进.
所以我需要匹配连续的前导空格(即每行开头的缩进),它们不是4的倍数,即数量为1,2,3,5,6,7,9,10,11的空格等
例如
>>> a = 1 # match this, as there're 3 spaces at the beginning
>>> b = a # match this too, as indent by 7 spaces
>>> c = 2 # but not this, since it's indented exactly by 4 spaces
>>> d = c # not this either, since indented by 8 spaces
Run Code Online (Sandbox Code Playgroud)
我能够使用以下内容匹配4个中的多个空格:
^( {16}| {12}| {8}| {4})
Run Code Online (Sandbox Code Playgroud)
然后我尝试将其与之相反的东西相匹配:
^[^( {16}| {12}| {8}| {4})]
Run Code Online (Sandbox Code Playgroud)
但它只匹配空行或行开头与一个字符,而不是我想要的.
我是正则表达式的完全新手,但我搜索了几个小时没有运气.我知道我总能匹配列出的所有非多数的4个数字,但我希望有人可以帮助并提供一种不那么繁琐的方法.
谢谢.
更新1
使用正则表达式(@ user2864740)
^(?:\s{4})*\s{1,3}\S
Run Code Online (Sandbox Code Playgroud)
或(@alpha bravo)
^(?!(\s{4})+\S)(.*)
Run Code Online (Sandbox Code Playgroud)
匹配非多重4的缩进,以及带有4(8,16等)空格的空行和它们后面的第一个非空行的第一个字符.
例如(在regex101.com上)
如何避免匹配上面示例中描述的这些情况?
use*_*740 10
字符类只能包含..一组字符,因此[^..]不适合一般否定.正则表达式[^( {16}| {12}| {8}| {4})]相当于[^( {16}|284]匹配未列出的每个字符.
现在,匹配不是 4个空格的倍数与查找n mod 4 = {1, 2, 3}(或除了 n mod 4 = 0)空格相同.这可以通过以下模式完成:
(?:\s{4})*\s{1,3}\S
Run Code Online (Sandbox Code Playgroud)
说明:
(?:\s{4})* - match any number of whole groups of 4 spaces and then ..
\s{1,3} - match any count of 1, 2, or 3 spaces such that ..
\S - they are not followed by a space
Run Code Online (Sandbox Code Playgroud)
正则表达式可能需要一个尾随dot-all(.*)或前导line-anchor(^),具体取决于它的使用方式.