“Scanner”这个名字有点误导,因为这个词经常被用来表示词法分析器,而这并不是 Scanner 的用途。所有这一切都只是替代品scanf()
你在 C、Perl 中找到的函数,et al。像 StringTokenizer 和split()
,它被设计为向前扫描,直到找到给定模式的匹配项,并且在途中跳过的任何内容都会作为令牌返回。
另一方面,词法分析器必须检查和分类每个字符,即使只是决定是否可以安全地忽略它们。这意味着,每次匹配后,它可能会应用多种模式,直到找到匹配的模式从那时开始。否则,它可能会找到序列“//”,并认为它找到了注释的开头,而实际上它位于字符串文字内,并且它只是没有注意到左引号。
当然,它实际上比这复杂得多,但我只是说明为什么像 StringTokenizer 这样的内置工具,split()
和扫描仪不适合此类任务。然而,可以使用 Java 的正则表达式类进行有限形式的词法分析。事实上,添加 Scanner 类使其变得更加容易,因为添加了新的 Matcher API 来支持它,即区域和usePattern()
方法。下面是一个基于 Java 正则表达式类构建的基本扫描器的示例。
import java.util.*;
import java.util.regex.*;
public class RETokenizer
{
static List<Token> tokenize(String source, List<Rule> rules)
{
List<Token> tokens = new ArrayList<Token>();
int pos = 0;
final int end = source.length();
Matcher m = Pattern.compile("dummy").matcher(source);
m.useTransparentBounds(true).useAnchoringBounds(false);
while (pos < end)
{
m.region(pos, end);
for (Rule r : rules)
{
if (m.usePattern(r.pattern).lookingAt())
{
tokens.add(new Token(r.name, m.start(), m.end()));
pos = m.end();
break;
}
}
pos++; // bump-along, in case no rule matched
}
return tokens;
}
static class Rule
{
final String name;
final Pattern pattern;
Rule(String name, String regex)
{
this.name = name;
pattern = Pattern.compile(regex);
}
}
static class Token
{
final String name;
final int startPos;
final int endPos;
Token(String name, int startPos, int endPos)
{
this.name = name;
this.startPos = startPos;
this.endPos = endPos;
}
@Override
public String toString()
{
return String.format("Token [%2d, %2d, %s]", startPos, endPos, name);
}
}
public static void main(String[] args) throws Exception
{
List<Rule> rules = new ArrayList<Rule>();
rules.add(new Rule("WORD", "[A-Za-z]+"));
rules.add(new Rule("QUOTED", "\"[^\"]*+\""));
rules.add(new Rule("COMMENT", "//.*"));
rules.add(new Rule("WHITESPACE", "\\s+"));
String str = "foo //in \"comment\"\nbar \"no //comment\" end";
List<Token> result = RETokenizer.tokenize(str, rules);
for (Token t : result)
{
System.out.println(t);
}
}
}
顺便说一句,这是我发现的唯一好的用途lookingAt()
方法。 :D