正则表达式根据之前匹配的内容进行匹配 [英] Regex to match something based on what was matched before

查看:255
本文介绍了正则表达式根据之前匹配的内容进行匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图编写一个正则表达式来验证代数象棋符号。这是我到目前为止的内容:

  / 
O-O(-O)? #Castling
| [KQRBN] x?[a-h] [1-8] \ +? #最正常的举动和捕获
/

我迷失的地方是典当促销。



骑士,主教或中央典当只能在其起始文件或通过捕获在任一侧的文件上进行提升。车子卒可以通过直线移动或捕获到一侧来提升,具体取决于它在a-或h-文件中。像这样的

  / [ah](x [ah])?[18] = [QRBN] \ +?/ 

不起作用,因为fxh8不是有效的动作(只有fxe8和fxg8是有效的)。我可以走很长一段路

  /(a(xb)?| h(xg)?| b(x [ac ])?... /#再插入5个文件代替... 

效率不高。我想使用分组功能,以便可以执行rook-pawns以及其他所有操作。

  /([bg])(x(\1±1))?/ 

表示字母b到g后面可能跟字母。

解决方案

匹配



有人刚刚发布了类似问题出于您的同情困境。



长路是唯一的方法。

I'm trying to write a regular expression to validate moves in algebraic chess notation. Here's what I have so far:

/
    O-O(-O)?                 # Castling
    |[KQRBN]x?[a-h][1-8]\+?  # Most normal moves and captures
/

Where I am lost is pawn promotion.

A knight, bishop, or centre pawn may only promote on the file from which it starts or the file on either side via a capture. A rook pawn may promote by moving straight or capturing to one side, depending on whether it is on the a- or h- files. So something like

/[a-h](x[a-h])?[18]=[QRBN]\+?/

doesn't work, because fxh8 is not a valid move (only fxe8 and fxg8 are). I could go the long route with

/(a(xb)?|h(xg)?|b(x[ac])?.../ # insert 5 more files in place of the ...

but that's not very efficient. I want to use grouping, so that I can do rook-pawns, and everything else. I have something like this in mind:

/([b-g])(x(\1±1))?/

To indicate "the letters b to g may be followed by the letter that comes before or after them".

解决方案

Matching the adjacent letter is not hard using alternations, but you won't find anything compact as there is no character arithmetic in regex.

Someone just posted a similar question out of sympathy for your plight.

The long way is the only way.

这篇关于正则表达式根据之前匹配的内容进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆