调试正则表达式

时间:2014-09-11 10:09:59

标签: java regex

我试图在java中为C ++源文件编写一个注入器。它只是加速代码编辑过程的基本工具。

我正在扫描的内容基本上是:

ClassName::FunctionName() {

我使用txt2re(http://txt2re.com)为我的搜索生成正则表达式,等于:

.*?(?:[a-z][a-z0-9_]*).*?((?:[a-z][a-z0-9_]*))(:)(:)((?:[a-z][a-z0-9_]*))(\\().*?(\\)).*?(\\{)

我的应用程序是用Java编写的,并且在我的测试文件上工作。现在我尝试用它扫描源代码的子目录以应用我的更改,但匹配器挂起。据说一些正则表达式没有优化甚至是错误的,因此挂起是有意义的。在正则表达式方面,我不是专家,而且使用它们的时候也不是很坚定(很少发生)。有没有办法加快匹配过程或纠正我的模式?

1 个答案:

答案 0 :(得分:0)

您的搜索是将要素分组,以便提取到替换表达式中。你需要吗?我假设你这样做。我删除了你不需要的空替代品(即“:?”),并将分组展平。如果你想要做的只是在识别匹配的行之后注入一些代码,它可以进一步展平。这是我从txt2re修改的一些代码:

import java.util.regex.*;

class Main
{
  public static void main(String[] args)
  {
    String txt=" ClassName::function_name123(char *p)  { ";

    String re1="([a-z][a-z0-9_]*)";    // match and group class name
    String re2="::";   // match and eat exactly ::
    String re3="([a-z][a-z0-9_]*)";    // match and group function name
    String re4="(\\(.*\\))";   // match and group round braces (and any parameters between them)
    String re5="\\s*"; // match and eat whitespace
    String re6="\\{";  // match and eat exactly {

    Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(txt);
    if (m.find())
    {
        String classname=m.group(1);
        String funcname=m.group(2);
        String params=m.group(3);
        System.out.println("I discovered that class "+classname+" has function "+funcname+params);
    }
  }
}
相关问题