[英]Using regex to extract substring
我正在嘗試為 PGN 文件移動制作解析器。 我想從移動 1 開始的總文本輸入中提取 substring。
這是一個 PGN 文件的示例:
我試圖通過正則表達式使用indexOf()
提取substring
中的動作。
這是我的嘗試:
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());
這是預期的 output:
1.Nf3 d5 2.g3 g6
indexOf
不適用於正則表達式。 改用search
。
它現在給出了預期的 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.