简体   繁体   English

我试图找出一个使用 (?(ID/NAME).....) 的正则表达式

[英]Im trying to figure out a regex with using (?(ID/NAME).......)

>>> p = re.compile(r'(((x)|y)(?(2)y|x))+')
>>> p.search('yxxyyx')
<_sre.SRE_Match object; span=(2, 4), match='xy'>

My questions: why it matches only 'xy'?我的问题:为什么它只匹配“xy”? and does \\2 always refer to "x" within the group (.......)+??并且 \\2 是否总是指组中的“x” (.......)+??

edited: Thank you for all your answers!编辑:感谢您的所有回答! I found a helpful website to make regex visualize.我找到了一个有用的网站来使正则表达式可视化。

Questions:问题:

  1. Why does it matches only 'xy'?为什么它只匹配“xy”?
  2. Does \\2 always refer to "x" within the group (.......)+?? \\2 是否总是指组中的“x” (.......)+??

Answer Question 2 first:先回答问题2:

In this regex, you are using:在此正则表达式中,您使用的是:

(?(id/name)yes-pattern|no-pattern)

Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn't.如果具有给定 id 或名称的组存在,将尝试与 yes-pattern 匹配,如果不存在则与 no-pattern 匹配。 no-pattern is optional and can be omitted. no-pattern 是可选的,可以省略。 For example, (<)?(\\w+@\\w+(?:.\\w+)+)(?(1)>) is a poor email matching pattern, which will match with '' as well as 'user@host.com', but not with '例如, (<)?(\\w+@\\w+(?:.\\w+)+)(?(1)>) 是一个糟糕的电子邮件匹配模式,它将与 '' 以及 'user@host 匹配。 com',但不带 '

In the regex given ((x)|y) , there is only one group before the question (?(2)y|x))+ that asks whether the second group has matched.在给定的正则表达式((x)|y) ,在问题(?(2)y|x))+之前只有一组询问第二组是否匹配。 Since there is only one group the conditional will always be false, and thus will always try to match x由于只有一组,因此条件将始终为假,因此将始终尝试匹配x

Answer Question 1:回答问题 1:

Yes, since there is only one group, the conditional will always match x , and the entire regex only match xyx是的,因为只有一组,条件总是匹配x ,整个正则表达式只匹配xyx

( DOCS ) 文档

我发现这个网站是学习和测试不同正则表达式模式的好资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我试图从网页中使用正则表达式python获取代理 - im trying to get proxies using regex python out of a web page 我试图找出 .csv 文件的最大值和最小值,但我无法弄清楚我做错了什么 - Im trying to figure out the max and min of a .csv file and i cant figure out what im doing wrong 我正在尝试使用 python 从 html 网站中提取一些数据 - im trying to extract some data out of html website using python 找出试图在一个模块python中使用导入的模块名称 - Figure out the module name trying to use imports in one module python 正在开发一个购买电影票的程序。 试图弄清楚我是否可能需要一个 while 循环来完成我想要完成的任务? - Working on a program for buying tickets to a movie. Trying to figure out if I maybe need a while loop for what im trying to accomplish? 我正在尝试淡入淡出 - Im trying to make a fade in and out 我是 python 的新手,我正在努力学习它,我不明白为什么一个结果给了我一个不同的结果 - Im new to python and am trying to learn it, I can't figure out why one outcome is giving me a different one 尝试弄清楚使用Django从数据库评估字符串的语法 - Trying to figure out syntax to evaluate a string from the database using Django 试图弄清楚of子手的游戏 - Trying to figure out a game of Hangman 试图找出块数据 - Trying to figure out block data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM