regex 如何重新格式化以Seat N开头的子字符串:图案

jxct1oxe  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(104)

如何替换符合以下模式格式的字符串

Seat x: SomeUsername collected ($1234.56)

Seat x: SomeUsername did not showed and won $1234.56

而不替换其他字符串?用户名可以包含空格。
范例:

...
PridvorD collected $582.00 from pot
PridvorD: doesn't show hand 
*** SUMMARY ***
Total pot $585.00 | Rake $3.00 
Board [5c Qc 2c 8d]
Seat 1: Walleater folded on the Flop
Seat 3: PridvorD collected ($582.00) # The only string that matches replacement pattern
Seat 4: KingsPower folded on the Flop
...

所需输出:

...
PridvorD collected $582.00 from pot
PridvorD: doesn't show hand 
*** SUMMARY ***
Total pot $585.00 | Rake $3.00 
Board [5c Qc 2c 8d]
Seat 1: Walleater folded on the Flop
Seat 3: PridvorD did not showed and won $582.00
Seat 4: KingsPower folded on the Flop
...
ttcibm8c

ttcibm8c1#

看起来是个很容易的案子

import re

def reformat_string(s):
    pattern = r'(Seat \d+:) (.*?)( collected \(\$([\d\.]+)\))'
    replacement = r'\1 \2 did not show and won $\4'
    return re.sub(pattern, replacement, s)

# Sample input
input_string = """
PridvorD collected $582.00 from pot
PridvorD: doesn't show hand 
*** SUMMARY ***
Total pot $585.00 | Rake $3.00 
Board [5c Qc 2c 8d]
Seat 1: Walleater folded on the Flop
Seat 3: PridvorD collected ($582.00) 
Seat 4: KingsPower folded on the Flop
"""

# Get the reformatted output
output_string = reformat_string(input_string)
print(output_string)

如果这还不够,请补充更多细节。

相关问题