正则表达式 - 匹配空格

mrj*_*min 7 regex compiler-construction lex lexical-analysis flex-lexer

我写一个正在修改输入中所有空格的正则表达式有一个大问题.

我试过了\s+,[ \t\t\r]+但那不起作用.

我需要这个,因为我正在使用flex编写一个扫描仪,我被困在匹配的空格中.空格应该匹配而不是删除.

输入示例:

program 
3.3 5 7 
{ comment }
string
panic: cant happen
Run Code Online (Sandbox Code Playgroud)

Mat*_*ery 12

  1. flex使用(大约)POSIX"扩展正则表达式"语法 - \s不起作用,因为它是Perl扩展.

  2. [ \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;
}
Run Code Online (Sandbox Code Playgroud)

...成功匹配示例输入中的空白(我保存为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: '
'
Run Code Online (Sandbox Code Playgroud)