0
我使用正則表達式來通過一些VB代碼使用正則表達式領先的單引號的字符串和我想要找的形式的陳述 -如何檢測和排除在Java中
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
如何編寫一個正則表達式來檢測行開頭的單引號(即不包括空格)並避免這些行?
所以我添加\ S *是多餘的,因爲[^'] *照顧它吧? – CodeBlue 2012-04-17 21:49:32
好的,我明白問題所在。謝謝。 – CodeBlue 2012-04-17 21:52:10