我在编写正则表达式时遇到了一个大问题,该正则表达式将修剪输入中的所有空白。
我已经尝试过\s+
和[ \t\t\r]+
了,但是不起作用。
我需要这样做,因为我正在使用flex编写扫描仪,并且停留在匹配的空白处。
空格应该只是匹配而不能删除。
输入示例:
program
3.3 5 7
{ comment }
string
panic: cant happen
最佳答案
flex
使用(大约)POSIX“扩展正则表达式”语法-\s
不起作用,因为它是Perl扩展名。 [ \t\t\r]+
是错字吗?我想您会在其中想要一个\n
。 像
[ \n\t\r]+
这样的东西当然应该可以工作。例如,此词法分析器(我将其保存为lexer.l
):%{
#include <stdio.h>
%}
%option noyywrap
%%
[ \n\t\r]+ { printf("Whitespace: '%s'\n", yytext); }
[^ \n\t\r]+ { printf("Non-whitespace: '%s'\n", yytext); }
%%
int main(void)
{
yylex();
return 0;
}
...成功匹配了示例输入中的空格(我将其保存为
input.txt
):$ flex lexer.l
$ gcc -o test lex.yy.c
$ ./test < input.txt
Non-whitespace: 'program'
Whitespace: '
'
Non-whitespace: '3.3'
Whitespace: ' '
Non-whitespace: '5'
Whitespace: ' '
Non-whitespace: '7'
Whitespace: '
'
Non-whitespace: '{'
Whitespace: ' '
Non-whitespace: 'comment'
Whitespace: ' '
Non-whitespace: '}'
Whitespace: '
'
Non-whitespace: 'string'
Whitespace: '
'
Non-whitespace: 'panic:'
Whitespace: ' '
Non-whitespace: 'cant'
Whitespace: ' '
Non-whitespace: 'happen'
Whitespace: '
'
关于regex - 正则表达式-匹配空格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13317319/