[英]Scanner - parsing code values using delimiter regex
我正在嘗試使用掃描程序從“p.addPoint(x,y);”形式的字符串中讀取代碼行。
我正在使用的正則表達式格式是:
*anything*.addPoint(*spaces or nothing*
OR ,*spaces or nothing*
我到目前為止所嘗試的不起作用: [[.]+\\\\.addPoint(&&[\\\\s]*[,[\\\\s]*]]
我有什么想法我做錯了嗎?
我在Python中對此進行了測試,但正則表達式應該可以轉換為Java:
>>> regex = '(\w+\.addPoint\(\s*|\s*,\s*|\s*\)\s*)'
>>> re.split(regex, 'poly.addPoint(3, 7)')
['', 'poly.addPoint(', '3', ', ', '7', ')', '']
你的正則表達式似乎嚴重錯誤。 即使它不是,匹配無數的重復.
字符串開頭的通配符可能會導致大量的文本匹配,這些匹配實際上並不相關/期望。
編輯:誤解了原始規格,目前的正則表達式應該是正確的。
其他方式:
public class MyPattern {
private static final Pattern ADD_POINT;
static {
String varName = "[\\p{Alnum}_]++";
String argVal = "([\\p{Alnum}_\\p{Space}]++)";
String regex = "(" + varName + ")\\.addPoint\\(" +
argVal + "," +
argVal + "\\);";
ADD_POINT = Pattern.compile(regex);
System.out.println("The Pattern is: " + ADD_POINT.pattern());
}
public void findIt(String filename) throws FileNotFoundException {
Scanner s = new Scanner(new FileReader(filename));
while (s.findWithinHorizon(ADD_POINT, 0) != null) {
final MatchResult m = s.match();
System.out.println(m.group(0));
System.out.println(" arg1=" + m.group(2).trim());
System.out.println(" arg2=" + m.group(3).trim());
}
}
public static void main(String[] args) throws FileNotFoundException {
MyPattern p = new MyPattern();
final String fname = "addPoint.txt";
p.findIt(fname);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.