如何使用Java中的正则表达式检测和排除String中的前导单引号

时间:2012-04-17 21:39:58

标签: java regex

我正在使用正则表达式来浏览一些VB代码,我想查找表单的语句 -

    ABC.Transaction = GlobalCommArea

不幸的是,代码中注释了一些语句。 VB单行注释以单引号开头,因此我的搜索结果如 -

        ' ABCD.Transaction = GlobalCommArea    <-- incorrect
  ' PQR.Transaction = GlobalCommArea           <-- incorrect
  WXY.Transaction = GlobalCommArea             <-- correct
      WXY.Transaction = GlobalCommArea ' 2012      <-- correct

我尝试使用以下代码检测是否存在单引号并将其排除 -

     public static void test2()
     {
    String[] lines = new String[20];

  lines[0] = "' ABCD.Transaction = GlobalCommArea";
  lines[1] = "   ' PQR.Transaction = GlobalCommArea";
  lines[2] = " WXY.Transaction = GlobalCommArea";
  lines[3] = "WXY.Transaction = GlobalCommArea ' 2012";

  String regex;
  regex = "^\\s*[^']*\\s*.*.Transaction\\s*=\\s*GlobalCommArea"; // the regex that I am using

      Pattern p = Pattern.compile(regex);


  for(int i=0; i<=3; i++)
  {
     Matcher m = p.matcher(lines[i]);

     if(m.find())
     {
        System.out.print("Yes\t");
     }
     else
     {
        System.out.print("No\t");
     }

      System.out.println(lines[i]);
     }
    }

但是,正则表达式不起作用。我得到了以下输出 -

    Yes ' ABCD.Transaction = GlobalCommArea
    Yes    ' PQR.Transaction = GlobalCommArea
    Yes  WXY.Transaction = GlobalCommArea
    Yes WXY.Transaction = GlobalCommArea ' 2012

如何编写一个正则表达式来检测行开头的单引号(即排除空格)并避免这些行?

1 个答案:

答案 0 :(得分:1)

由于.*之前的Transaction,您正在匹配所有这些内容,请尝试将其更改为以下内容:

regex = "^[^']*\\.Transaction\\s*=\\s*GlobalCommArea";