簡體   English   中英

如何在Java中使用正則表達式檢測和排除字符串中的前導單引號

[英]How to detect and exclude leading single quote in a String using regex in Java

我正在使用正則表達式來查看一些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

如何編寫一個正則表達式來檢測行首(即不包括空格)的單引號,並避免出現這些行?

由於Transaction前的.* ,您將所有這些匹配,請嘗試將其更改為以下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM