[英]Using regex to extract substring
I am trying to make a parser for PGN-file moves.我正在尝试为 PGN 文件移动制作解析器。 I would like to extract a substring from the total text-input starting from move 1.
我想从移动 1 开始的总文本输入中提取 substring。
This is an example piece of a PGN file:这是一个 PGN 文件的示例:
I tried to extract the moves in a substring
using indexOf()
by a regex.我试图通过正则表达式使用
indexOf()
提取substring
中的动作。
This is my attempt:这是我的尝试:
function extractMoves(){ const pgn = '[Date "2013.11.12"] 1.Nf3 d5 2.g3 g6'; // Sample PGN. const firstMove = /1\.([ah]|[NBRQK])/; // First move regex. const moves = pgn.substring(pgn.indexOf(firstMove)); return moves; } console.log(extractMoves());
This is the expected output:这是预期的 output:
1.Nf3 d5 2.g3 g6 1.Nf3 d5 2.g3 g6
indexOf
doesn't work with regex. indexOf
不适用于正则表达式。 Use search
instead.改用
search
。
It gives the expected output now:它现在给出了预期的 output:
function extractMoves(){
const pgn = '[Date "2013.11.12"] 1.Nf3 d5 2.g3 g6'
const firstMove = /1\.([a-h]|[NBRQK])/;
const moves = pgn.substring(pgn.search(firstMove));
return moves;
}
console.log(extractMoves());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.