I have a file stored and I'm reading it with Javascript. The problem is that I want to simulate a syntactic validator and I can't get a good result.

syntax.txt:

class foo {
}

The problem is that I can't get the class content. What I do is verify if there's a class statement:

fileString.match(\^class\g);

This returns me: ["class"], but I want to get foo { } and everething inside.

This is possible?

And what happend if the file changes? something like: syntax.txt:

class foo {
}
class bar {
}

Thanks!

有帮助吗?

解决方案

You aren't going to be able to validate a programming language with regex, for the same reason you can't validate HTML with regex. It's not regular.

Imagine this (pseudo code):

class foo {
    function barbar() {
        if(foobar) {
            case(bar) {
                'x': ... break;
                'y':
                    if(foofoo) {
                        ...
                        return "}";
                    }
            }
        }
    }
}

You'll never be able to handle all of the scenarios in regex. You need a true parser. You can write your own or use a library, but you definitely cannot rely on regex for this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top