在正则表达式中使用字母选择器的问题

时间:2018-09-16 11:09:46

标签: python regex

我的字符串看起来像这样:

print("Choose the type of game(1:Easy;2 Difficult)")
levelinput = int(input())

print("")


print("Enter the number of moves")

number_of_moves = int(input())
i =1
x = 79
randomvalue = (22695477*x+1)%2**31
x2 = randomvalue
machine = int()


while i <= number_of_moves:
    print("")
    print("Choose your move number", i ,"(0 or 1)")

    move_selection = int(input())

    if i  == 1:
        randomvalue = (22695477*x+1)%2**31

    else:
        randomvalue = (22695477*x2+1)%2**31

    i = i +1


    if randomvalue <= 2**31:
        machine == int(0)
    else:
        machine == int(1)

    def resultgame (move_selection,machine):
        if move_selection == machine:
            return("Computer Wins")
        else:
            return("Player Wins")

    result = resultgame

    print("player = ", move_selection, "machine = ", machine,"-", result(move_selection,machine))

我只希望以上字符串中的"Jothijohnsamyperiyasamy" 。正则表达式,

"Jothijohnsamy"

打印'Jo\w+samy' ,但我只需要"Jothijohnsamyperiyasamy"。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

尝试非贪婪匹配:

>>> re.compile(r"Jo\w+?samy").match("Jothijohnsamyperiyasamy")
<_sre.SRE_Match object; span=(0, 13), match='Jothijohnsamy'>
>>> _.group()
'Jothijohnsamy'

+?令牌的意思是“匹配1次或多次,但要尽可能少。没有问号,它的含义是“匹配1次或多次,并尽可能多”。

另一个简单的示例:对于字符串"aaaaaa",正则表达式a+匹配所有字符,但是a+?仅匹配一个(尽可能少),而a*?匹配没有。