为什么在数据(d)上应用正则表达式(rx)给出输出(o)?
正则表达式(rx):
s/(?<!\#include)[\s]*\<[\s]*([^\s\>]*)[\s]*\>/\<$1\>/g
Run Code Online (Sandbox Code Playgroud)
数据(d):
#include <a.h> // 2 spaces after e
Run Code Online (Sandbox Code Playgroud)
输出(o):
#include <a.h> // 1 space is still there
Run Code Online (Sandbox Code Playgroud)
预期产出是:
#include<a.h> // no space after include
Run Code Online (Sandbox Code Playgroud)
(?<!\#include)当你通过两个空格中的第一个时,条件为真,因此匹配从那里开始.
#include <a.h>
^^^^^^- matched by your regex.
Run Code Online (Sandbox Code Playgroud)
这意味着您的替换操作不会移除空间.
如果您使用正向lookbehind断言,您将获得所需的结果:
s/(?<=#include)\s*<\s*([^\s>]*)\s*>/<$1>/g;
Run Code Online (Sandbox Code Playgroud)
可以重写以使用更高效\K:
s/#include\K\s*<\s*([^\s>]*)\s*>/<$1>/g;
Run Code Online (Sandbox Code Playgroud)