python - 如何使用正则表达式对非常具体的模式进行分组?

标签 python regex

Problem:

https://coderbyte.com/editor/Simple%20Symbols

The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.

Input:"+d+=3=+s+"

Output:"true"

Input:"f++d+"

Output:"false"

我正在尝试为以下问题创建正则表达式,但我不断遇到各种问题。如何生成返回指定规则('+\D+')的内容?

import re
plusReg = re.compile(r'[(+A-Za-z+)]')
plusReg.findall()
>>> []

在这里,我想我可以创建自己的类来搜索模式。

import re
plusReg = re.compile(r'([\\+,\D,\\+])')
plusReg.findall('adf+a+=4=+S+')
>>> ['a', 'd', 'f', '+', 'a', '+', '=', '=', '+', 'S', '+']

在这里,我认为“\\+”会挑出加号并将其读取为字符。

mo = plusReg.search('adf+a+=4=+S+')
mo.group()
>>>'a'

这里使用相同的 shell,我尝试使用搜索而不是 findall,但我只是得到了第一个字母,它甚至没有被加号包围。

我的最终结果是将字符串 'adf+a+=4=+S+' 分组为 ['+a+','+S+'] 等。

最佳答案

一种方法是在字符串中搜索符合以下条件的任何字母:(1) 前面有 +,或 (2) em> 后跟一个 +。这可以使用前瞻和后瞻断言来完成:

>>> rgx = re.compile(r'(?<!\+)[a-zA-Z]|[a-zA-Z](?!\+)')

因此,如果 rgx.search(string) 返回 None,则该字符串有效:

>>> rgx.search('+a+') is None
True
>>> rgx.search('+a+b+') is None
True

但如果它返回匹配项,则该字符串无效:

>>> rgx.search('+ab+') is None
False
>>> rgx.search('+a=b+') is None
False
>>> rgx.search('a') is None
False
>>> rgx.search('+a') is None
False
>>> rgx.search('a+') is None
False

关于前瞻/后瞻断言的重要一点是它们不消耗字符,因此它们可以处理重叠匹配。

关于python - 如何使用正则表达式对非常具体的模式进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41369550/

相关文章:

regex - Notepad++、Posix 正则表达式和 URL(用于获取域的正则表达式)

python - 在 python 2.7 Windows 上安装 libxml2

python - 一个带有 'while' 的线程 python 得到另一个线程从未启动

java - 使用模式/匹配器提取子字符串

Java 字符串附加双引号

regex - 在 50,000 个 HTML 页面中查找电话号码

python - 使用 BeautifulSoup 解析一个父级中的多个 href

python - 如何使用 Boto3 按上次修改日期过滤 s3 对象

python - 错误: no matching function for call to ‘CBNET::CBNET(boost::reference_wrapper<const CBNET>::type&)’

VBA 中所有匹配项的正则表达式数组/列表/集合