仅考虑第一个匹配项(Python Re)
字符串中以给定字符串开头和结尾的不同子字符串 给定一个字符串s和另外两个字符串begin和end,查找字符串中以给定begin和end字符串开头和结尾的不同子字符串的数目 示例:仅考虑第一个匹配项(Python Re),python,regex,Python,Regex,字符串中以给定字符串开头和结尾的不同子字符串 给定一个字符串s和另外两个字符串begin和end,查找字符串中以给定begin和end字符串开头和结尾的不同子字符串的数目 示例: Input : s = "geeksforgeeks" begin = "geeks" end = "for" Output : 1 Input : s = "vishakha" begin = "h" end = "a" Output : 2 Two
Input : s = "geeksforgeeks"
begin = "geeks"
end = "for"
Output : 1
Input : s = "vishakha"
begin = "h"
end = "a"
Output : 2
Two different sub-strings are "ha" and "hakha".
我目前的做法
import re
def find_from_right(string,reg):
s = ""
match = []
for c in string:
s = s+c
for i in re.findall(reg, s):
match.append(i)
return match
print(find_from_right(str(raw_input()),r".*c.*d$"))
输出:['cod','codepppforfood']
问题是它与以下字符串不匹配:
cppforfood
它只考虑第一场比赛。
有人能指出错误吗?您可以将
re.compile
和re.findall
与regex
模块相结合,找到重叠的匹配项
import regex
s = "geeksforgeeks"
begin = "geeks"
end = "for"
first_pattern = regex.compile(''.join(begin+'[a-zA-Z]*'+end))
print(regex.findall(first_pattern,s,overlapped=True));
s = "vishakha"
begin = "h"
end = "a"
second_pattern = regex.compile(''.join(begin+'[a-zA-Z]*'+end))
print(regex.findall(second_pattern,s,overlapped=True));
上面的代码打印:
['geeksfor']
['hakha', 'ha']
您可以使用正则表达式在字符串中查找所有出现的开始符号和结束符号,并使用列表理解构造答案:
s = input("Enter String: ")
head = input("Enter start: ")
tail = input("Enter end: ")
result = list(set([s[i.start():j.start() + 1]
for i in re.finditer(head, s) for j in re.finditer(tail, s)
if i.start() < j.start()]))
print(result)
我建议你改变题目,我相信这就是你被否决的原因。谢谢。将这样做:)它说:TypeError:findall()得到了一个意外的关键字参数“重叠”,就像我说的,这与regex模块一起工作,你是否安装了
regex
模块?这不起作用,因为vishakha
作为输入,而h
作为开始,而a
在结束时只打印['hakha'
['cod', 'codecppforfood', 'cppforfood']