我有两个表达式应该是有效的,但却没有被识别为有效。

2024-06-17 11:28:30 发布

您现在位置:Python中文网/ 问答频道 /正文

import re

cards1 = "'F'*4 + 'H'*10"; cards2 = 'FFHH'
def find_number_of_cards(cards):
    regexp = re.compile(r"(?P<FandH>[FH]+) | (('F')[*](?P<F>[0-9]+)\s*[+]\s*('H')[*](?P<H>[0-9]+))")
    result = regexp.search(cards)
    if result == None:
        return ("The expression given is not valid.")
    else:
        FnH = result.group('FandH')
        F = result.group('F')
        H = result.group('H')
        if FnH == None:
            return F, H
        else:
            return "Blank."

print(find_number_of_cards(cards1))
print(find_number_of_cards(cards2))

Tags: ofrenonenumberreturnifgroupresult
1条回答
网友
1楼 · 发布于 2024-06-17 11:28:30

更改此项:

regexp = re.compile(r"(?P<FandH>[FH]+) | (('F')[*](?P<F>[0-9]+)\s*[+]\s*('H')[*](?P<H>[0-9]+))")

对此:

regexp = re.compile(r"(?P<FandH>[FH]+)|(('F')[*](?P<F>[0-9]+)\s*[+]\s*('H')[*](?P<H>[0-9]+))")

它在字符串中寻找一个不存在的空格

相关问题 更多 >