使用正则表达式提取子字符串

我正在尝试为PGN文件移动创建解析器。我想从移动1开始的总文本输入中提取一个子字符串。

这是 PGN 文件的示例部分:

断续器

我试图通过正则表达式在使用中提取移动。substringindexOf()

这是我的尝试:

function extractMoves(){

    const pgn = '[Date "2013.11.12"] 1.Nf3 d5 2.g3 g6'; // Sample PGN.

    const firstMove = /1\.([a-h]|[NBRQK])/; // First move regex.

    const moves = pgn.substring(pgn.indexOf(firstMove));

    return moves;

}

console.log(extractMoves());

这是预期的输出:

1.Nf3 d5 2.g3 g6


烙印99
浏览 77回答 1
1回答

ABOUTYOU

indexOf不适用于正则表达式。请改用。search它现在给出了预期的输出: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());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript