regex - Flex(适合正则表达式)- 匹配以相同字符开头和结尾的字符串

标签 regex apache-flex

(我转义了所有引号,这可能会使其难以阅读)

我需要在 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]);

痕迹

text
that
starts

正则表达式解释:

\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
            */

关于regex - Flex(适合正则表达式)- 匹配以相同字符开头和结尾的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1635254/

相关文章:

c# - RegEx 解析 XML 文件并仅返回带有文件扩展名的 url

javascript - 正则表达式删除JSON中未使用的所有特殊字符

Python findall() 起始数字和结束单词

apache-flex - 如何仅在 flex 中设置一个组件的工具提示延迟?

javascript - 我如何在 Javascript 和 Flex 之间进行通信?

匹配 4 组字母/数字的正则表达式,用连字符分隔

python - 在 Python 中使用正则表达式匹配 JSON 键

apache-flex - Flex - ResizeEvent.RESIZE 的问题

css - flex css 透明度

java - BlazeDS vs GraniteDS - 2 年后