(我将所有引号都转义了,这可能使阅读变得困难)
我需要匹配在flex中以相同字符开头和结尾的字符串...我知道很长的路(RE是-\“ a [^(a \”)] a \“ | \” b [^( b \“)b \” |等...),但我很肯定这不是我要做的(明天中期!);
我需要在flex中执行此操作,但是如果您能想到一个简短的正则表达式,则可以将其转换为flex表示法。
我当时想的是-
%%
int firstChar;
%x string;
%%
\"[A-Za-z] { firstChar = yytext+1; /* to get first character,
for people unfamiliar
with c pointers */
BEGIN(string);}
<string>[^((firstChar)\")] {}
<string>[(firstChar)\"] { BEGIN(INITIAL); }
(flex新手,可能是不正确的符号)
但是,这从几个方面困扰着我,首先,拥有该变量使它不成为常规语言。第二,我不知道您是否甚至可以在模式匹配中使用变量;第三,如果只是普通字符串,我不知道如何不匹配它。第三,我不知道如何返回在“字符串”中匹配的所有内容
谢谢你的帮助!
最佳答案
使用backreference。 \1
到\9
是指正则表达式使用括号()
捕获的前九组。
var regex:RegExp = /\b([a-zA-Z])\w+\1\b/g;
var test:String = "some text that starts and ends with same letter";
var result:Object;
while(result = regex.exec(test))
trace(result[0]);
痕迹
文本
那
开始
正则表达式解释:
\b //word boundary
([a-zA-Z]) //capture the first character
\w+ //one or more characters (use * to capture two letter words)
\1 //the first character
\b //word boundary
g /*
make the regex global. Without this, the program will will
print the first match ('text') in an infinite loop
*/