简体   繁体   English

扫描程序 - 使用分隔符正则表达式解析代码值

[英]Scanner - parsing code values using delimiter regex

I'm trying to use a Scanner to read in lines of code from a string of the form "p.addPoint(x,y);" 我正在尝试使用扫描程序从“p.addPoint(x,y);”形式的字符串中读取代码行。

The regex format I'm after is: 我正在使用的正则表达式格式是:

*anything*.addPoint(*spaces or nothing* OR ,*spaces or nothing* *anything*.addPoint(*spaces or nothing* OR ,*spaces or nothing*

What I've tried so far isn't working: [[.]+\\\\.addPoint(&&[\\\\s]*[,[\\\\s]*]] 我到目前为止所尝试的不起作用: [[.]+\\\\.addPoint(&&[\\\\s]*[,[\\\\s]*]]

Any ideas what I'm doing wrong? 我有什么想法我做错了吗?

I tested this in Python, but the regexp should be transferable to Java: 我在Python中对此进行了测试,但正则表达式应该可以转换为Java:

>>> regex = '(\w+\.addPoint\(\s*|\s*,\s*|\s*\)\s*)'
>>> re.split(regex, 'poly.addPoint(3, 7)')
['', 'poly.addPoint(', '3', ', ', '7', ')', '']

Your regexp seems seriously malformed. 你的正则表达式似乎严重错误。 Even if it wasn't, matching infinitely many repetitions of the . 即使它不是,匹配无数的重复. wildcard character at the beginning of the string would probably result in huge swaths of text matching that aren't actually relevant/desired. 字符串开头的通配符可能会导致大量的文本匹配,这些匹配实际上并不相关/期望。

Edit: Misunderstood the original spec., current regexp should be correct. 编辑:误解了原始规格,目前的正则表达式应该是正确的。

Another way: 其他方式:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM