我在编写一个将修剪输入中所有空格的正则表达式时遇到了一个大问题。
我已经尝试过\s+
,[ \t\t\r]+
但这不起作用。
我需要这个,因为我正在使用 flex 编写扫描仪,并且我被困在匹配空白处。空格应该只是匹配而不是删除。
示例输入:
program
3.3 5 7
{ comment }
string
panic: cant happen
我在编写一个将修剪输入中所有空格的正则表达式时遇到了一个大问题。
我已经尝试过\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: '
'
我不是 flex 方面的专家,但是您是否应该在正则表达式中使用 /g 和 /m 标志来处理多行字符串。