js实现Scanner
实现基础文本扫描功能
使用字符串的 index 和 substring 方法可以模拟基础扫描功能。以下代码演示如何按空格分割输入字符串:
class TextScanner {
constructor(text) {
this.text = text;
this.position = 0;
this.delimiter = ' ';
}
next() {
const end = this.text.indexOf(this.delimiter, this.position);
if (end === -1) {
const result = this.text.substring(this.position);
this.position = this.text.length;
return result;
}
const result = this.text.substring(this.position, end);
this.position = end + 1;
return result;
}
hasNext() {
return this.position < this.text.length;
}
}
支持自定义分隔符
扩展扫描器功能使其支持多种分隔符模式:
class EnhancedScanner {
constructor(text) {
this.text = text;
this.position = 0;
this.delimiters = [' ', '\t', '\n'];
}
setDelimiters(delimiters) {
this.delimiters = delimiters;
}
next() {
let minIndex = this.text.length;
for (const delim of this.delimiters) {
const index = this.text.indexOf(delim, this.position);
if (index !== -1 && index < minIndex) {
minIndex = index;
}
}
const result = this.text.substring(this.position, minIndex);
this.position = minIndex === this.text.length ? minIndex : minIndex + 1;
return result;
}
}
实现正则表达式匹配
对于更复杂的扫描需求,可以使用正则表达式:
class RegexScanner {
constructor(text) {
this.text = text;
this.position = 0;
this.pattern = /\s+/;
}
setPattern(pattern) {
this.pattern = new RegExp(pattern);
}
next() {
const remaining = this.text.slice(this.position);
const match = remaining.match(this.pattern);
if (!match || match.index !== 0) {
const result = remaining;
this.position = this.text.length;
return result;
}
const result = remaining.substring(0, match.index);
this.position += match.index + match[0].length;
return result;
}
}
处理数字和特殊类型
添加特定类型扫描方法:
class TypedScanner extends TextScanner {
nextInt() {
const token = this.next();
return parseInt(token, 10);
}
nextFloat() {
const token = this.next();
return parseFloat(token);
}
nextLine() {
const oldDelim = this.delimiter;
this.delimiter = '\n';
const result = this.next();
this.delimiter = oldDelim;
return result;
}
}
浏览器环境中的输入扫描
在浏览器中处理输入框内容:
function createInputScanner(inputId) {
const input = document.getElementById(inputId);
return {
next: () => {
const value = input.value.trim();
input.value = '';
return value;
}
};
}
Node.js 控制台输入处理
使用 Node.js 的 readline 模块实现交互式扫描:

const readline = require('readline');
async function createCLIScanner() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return {
next: () => new Promise(resolve => {
rl.question('', answer => resolve(answer));
}),
close: () => rl.close()
};
}
这些实现提供了不同级别的文本扫描功能,可以根据具体需求选择合适的方案。基础版本适合简单字符串处理,而正则表达式版本则能应对更复杂的文本解析需求。






