正则表达式匹配字符串 [英] Regex matching string

查看:145
本文介绍了正则表达式匹配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个编译器,我想做的一件事是使用'+'进行字符串连接,例如:

I am implementing a compiler and one thing I'd like to do is the string concatenation using '+', eg:

str_cnct = "hi" + "dear"

所以现在的值是"hidear".

So the value now is "hidear".

问题是我在flex中的正则表达式直接将所有正则表达式捕获为一个字符串,给出"hi + dear". 我当前的正则表达式是:\".*\"

The problem is that my regex in flex captures all of it directly as a string giving "hi + dear". My current regex is: \".*\"

{string}                {
                            yylval.struct_val.val.chain = (char *)malloc(sizeof(char)*yyleng);
                            strncpy(yylval.struct_val.val.chain,yytext,yyleng);
                            remove_char(yylval.struct_val.val.chain);
                            yylval.struct_val.length = yyleng;
                            yylval.struct_val.line = yylineno;
                            yylval.struct_val.column = columnno + yyleng + 2;
                            printf("--- String: %s\n", yylval.struct_val.val.chain);
                            return(STRING);
                    }

如何避免这种情况,并先捕捉"hi"然后捕捉"+"作为运算符,再捕捉亲爱的"?

How to avoid this and capture "hi" then '+' as operator and then "dear"?

预先感谢

推荐答案

尝试以下操作:

^\"([^\"]*)\"\s*\+\s*\"([^\"]*)\"$

$ 1将捕获不带引号的"hi",而$ 2将捕获不带引号的字符串"hi" +"dear"'.

$1 will capture "hi" w/o quotes and $2 will capture "dear" w/o quotes for string '"hi" + "dear"'.

这篇关于正则表达式匹配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆