gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:31 25 4
gpt4 key购买 nike

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+'] 等等。

编辑:

解决方法:

import re
def SimpleSymbols(str):
#added padding, because if str = 'y+4==+r+'
#then program would return true when it should return false.
string = '=' + str + '='
#regex that returns false if a letter *doesn't* have a + in front or back
plusReg = re.compile(r'[^\+][A-Za-z].|.[A-Za-z][^\+]')
#if statement that returns "true" if regex doesn't find any letters
#without a + behind or in front
if plusReg.search(string) is None:
return "true"
return "false"

print SimpleSymbols(raw_input())

我从 ekhumoro 和 Sanjay 那里借用了一些代码。谢谢

最佳答案

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

>>> 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

look ahead/behind 断言的重要之处在于它们不消耗字符,因此它们可以处理重叠匹配。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com