用于语法着色方案的正则表达式

时间:2018-04-21 15:33:51

标签: regex

我正在为我最喜欢的编程语言OOREXX开发语法着色方案。这种语言并不重要,因为我的问题纯粹是关于REGEX。

简单描述:正则表达式匹配任何一堆单词,但它们必须有一个"〜"前缀或"("后缀或两者

完整描述: 我想要匹配任何一堆或单词。它们是函数的名称。这很简单,例如:

(stream | Strip | Substr)等。

但是" strip" (例如)当我的代码不是函数名时可能会出现:

Strip = 1 - 设置变量" Strip"到1

所以,我需要更精确。函数名称必须具有前导"〜"或尾随"("或两者

这是我的REGEX技能失败的地方。我可以通过使用两个元素来解决这个问题,一个用于捕捉" ~strip"和一个捕捉"剥离("但这意味着复制和维护功能名称列表。这与谷物相反......

2 个答案:

答案 0 :(得分:1)

只需使用轮换。如果支持lookbehinds,您可以使用

(?<=~)strip|strip(?=\()

如果你想要一些花哨的东西并且你的正则表达式引擎支持lookbehind和if子句,你可以避免交替 - 虽然它不会再具有性能,例如

((?<=~))?strip(?(1)|(?=\())

如果你没有外观,你仍然可以使用分组并从捕获的组中提取,例如

~(strip)|(strip)\(

答案 1 :(得分:0)

我建议使用http://regexr.com测试正则表达式(over&over; over)。我不隶属于他们,但我每天8小时编写正则表达式(有时候)...这是练习它们的好工具.... 来回答你的问题(用Java)......

确保在下面的代码之后查看屏幕捕获图像。

// If there is a matching function name within this string, this will
// return that name, otherwise, it will return null.
public static String functionName(String functionNameStr)
{
    // This Regular Expression Groups the symbols before, or after, or both!
    // No, really, that's what it says...

    String  RE = "(~\\w+|\\w+\\)|~\\w+\\))";

    // NOTE: In Java, escape characters need to be Escaped Twice!
    // ALSO NOTE: This version puts a "precedence" on catching both symbols!
    // RE = "(~\\w+\\)|~\\w+|\\w+\\))"
    // Since the ~func-name) is listed first, if both symbols are included,
    // it will catch that too.  Maybe this is relevant to your code/question.

    Pattern P1 = Pattern.compile(RE);
    Matcher m  = P1.matcher(functionNameStr); 
    if (m.find())  return m.group();
    else           return null;
}

Click Here to see Screen Capture Image of Regular Expressions processor