kach / nearley

📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
https://nearley.js.org
MIT License
3.57k stars 232 forks source link

Expressing `this` but not `that` #538

Open pyoor opened 3 years ago

pyoor commented 3 years ago

I'm trying to translate the W3C ABNF notation into nearley and I'm not quite sure how to express a rule that matches anything matching this but not that as per:

A - B # matches any string that matches A but does not match B.

Is this possible without using a preprocessor?

sirjameswood commented 3 years ago

Sorta works...

"A - B" will be rejected, but "A - C" will pass.

expression -> [A-Z] " - " [A-Z] {%
    function(data, location, reject) {
        if(data[2] === "B") {
            return reject;
        } else {        
            return data;
        }
    }
%}

Or this...

"A - B" will be rejected, but "A - 1" will pass.

expression -> [A-Z] " - " [^A-Z]

But I'm guessing you want to specific one value rather than two? In which case use the function to reject? Not as clean as "A - B", but workable.

expression -> [A-Z] {%
    function(data, location, reject) {
        if(data[0] === "B") {
            return reject;
        } else {        
            return data;
        }
    }
%}