英文:
Is it possible to exec regex one character at once?
问题
我想使用正则表达式作为状态机,每次只处理一个字符。
示例:
// this matches only 13 or 123
const createStateMachine = () => {
const machine = {
"": {
1: "1",
},
1: {
2: "2",
3: "3",
},
2: {
3: "3",
},
};
let state = "";
return (value) => {
const nextState = machine[state][value];
if (nextState) {
state = nextState;
return true;
}
return false;
};
};
const exec = createStateMachine();
document.querySelector("input").addEventListener("keydown", (event) => {
if (!exec(event.key)) {
event.preventDefault();
}
});
这个输入只允许输入13和123:
<input>
以下是正则表达式版本,但显然不起作用:
const regex = /^12?3$/;
document.querySelector("input").addEventListener("keydown", (event) => {
if (!regex.exec(event.key)) {
event.preventDefault();
}
});
是否可以使用内置的正则表达式对象来实现这个目标?
英文:
I want to use regex like a state machine, feeding only one character at a time.
Example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// this matches only 13 or 123
const createStateMachine = () => {
const machine = {
"": {
1: "1",
},
1: {
2: "2",
3: "3",
},
2: {
3: "3",
},
};
let state = "";
return (value) => {
const nextState = machine[state][value];
if (nextState) {
state = nextState;
return true;
}
return false;
};
};
const exec = createStateMachine();
document.querySelector("input").addEventListener("keydown", (event) => {
if (!exec(event.key)) {
event.preventDefault();
}
});
<!-- language: lang-html -->
This input allows only 13 and 123
<input>
<!-- end snippet -->
And here is the regex version but it obviously doesn't work:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const regex = /^12?3$/
document.querySelector("input").addEventListener("keydown", (event) => {
if (!regex.exec(event.key)) {
event.preventDefault();
}
});
<!-- language: lang-html -->
<input>
<!-- end snippet -->
It is possible to use the built-in regex object for that?
答案1
得分: 2
可以使用内置的正则表达式对象吗?
不可以。
您可以解析正则表达式并从中构建自己的状态机,或者编写(或生成)一个匹配正则语言任何前缀的正则表达式,但是这两者都没有内置方法。
英文:
> It is possible to use the built-in regex object for that?
No.
You can either parse the regular expression and build your own state machine from that, or you write (or generate) a regular expression that matches any prefix of the regular language, but there exist no builtin methods for either of this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论