xhUsing Regex to find instances of a headr, then editing the lines below with some specifications

So I have this excerpt of the .msg file below. What I wish to do is for all the [sel xxx xxx] headers find them then read the lines below them. If any of the answers contain a (+3) or any (+x) then remove this from the message. Afterwards I want to compare each [sel xxx xxx] block and for the one with the highest (+x) I want to add another tag [clr 4] to it after the initial tags on the line but before the text. If there are two answers with equal (+x) then I wish to add [clr 4] to both lines.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[msg MSG_015_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Dummy[n][f 1 3 65535][w][e]
[sel SEL_016_0_0 top]
[s]A(+3)[e]
[s]B[e]
[s]C(+3)[e]
[msg MSG_021_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Sorry I had to ask something so[n]unreasonable... I appreciate you[n]going along with it, though.[n][f 1 3 65535][w][e]
[sel SEL_023_0_0 top]
[s]Fist! Of! Justice![e]
[s]Report him to the police.[e]
[s][f 0 8 2 1 2217]Try to reach out to her.(+3)[clr 27][e]
</code>
<code>[msg MSG_015_0_0 [Makoto]] [s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Dummy[n][f 1 3 65535][w][e] [sel SEL_016_0_0 top] [s]A(+3)[e] [s]B[e] [s]C(+3)[e] [msg MSG_021_0_0 [Makoto]] [s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Sorry I had to ask something so[n]unreasonable... I appreciate you[n]going along with it, though.[n][f 1 3 65535][w][e] [sel SEL_023_0_0 top] [s]Fist! Of! Justice![e] [s]Report him to the police.[e] [s][f 0 8 2 1 2217]Try to reach out to her.(+3)[clr 27][e] </code>
[msg MSG_015_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Dummy[n][f 1 3 65535][w][e]

[sel SEL_016_0_0 top]
[s]A(+3)[e]
[s]B[e]
[s]C(+3)[e]


[msg MSG_021_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Sorry I had to ask something so[n]unreasonable... I appreciate you[n]going along with it, though.[n][f 1 3 65535][w][e]

[sel SEL_023_0_0 top]
[s]Fist! Of! Justice![e]
[s]Report him to the police.[e]
[s][f 0 8 2 1 2217]Try to reach out to her.(+3)[clr 27][e]

So the output should look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[msg MSG_015_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Dummy[n][f 1 3 65535][w][e]
[sel SEL_016_0_0 top]
[s][clr 4]A[e]
[s]B[e]
[s][clr 4]C[e]
[msg MSG_021_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Sorry I had to ask something so[n]unreasonable... I appreciate you[n]going along with it, though.[n][f 1 3 65535][w][e]
[sel SEL_023_0_0 top]
[s]Fist! Of! Justice![e]
[s]Report him to the police.[e]
[s][f 0 8 2 1 2217][clr 4]Try to reach out to her.[clr 27][e]
</code>
<code>[msg MSG_015_0_0 [Makoto]] [s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Dummy[n][f 1 3 65535][w][e] [sel SEL_016_0_0 top] [s][clr 4]A[e] [s]B[e] [s][clr 4]C[e] [msg MSG_021_0_0 [Makoto]] [s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Sorry I had to ask something so[n]unreasonable... I appreciate you[n]going along with it, though.[n][f 1 3 65535][w][e] [sel SEL_023_0_0 top] [s]Fist! Of! Justice![e] [s]Report him to the police.[e] [s][f 0 8 2 1 2217][clr 4]Try to reach out to her.[clr 27][e] </code>
[msg MSG_015_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Dummy[n][f 1 3 65535][w][e]

[sel SEL_016_0_0 top]
[s][clr 4]A[e]
[s]B[e]
[s][clr 4]C[e]


[msg MSG_021_0_0 [Makoto]]
[s][bup 0 6 0 65535 1][f 4 10 65535 0 0][vp 8 0 0 0 65535 0]Sorry I had to ask something so[n]unreasonable... I appreciate you[n]going along with it, though.[n][f 1 3 65535][w][e]

[sel SEL_023_0_0 top]
[s]Fist! Of! Justice![e]
[s]Report him to the police.[e]
[s][f 0 8 2 1 2217][clr 4]Try to reach out to her.[clr 27][e]

I’ve been trying to write different pieces of code today but I’m very inexperienced with coding and I can never actually get it to run properly with the desired outcomes. I tried to solve it methodically by:

  1. Identifying the [sel headers using regex.
  2. Find any instances of (+x) and removing them
  3. Prepending [clr 4] before the text of the line with maximum (+x).
  4. Writing this back to an output file without any formatting changes (i.e. linebreaks stay the same, headers stay intact and it’s mostly unchanged).

This is my attempt:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import re
def process_block(block):
# Find all instances of `(+x)` and their positions in the block
plus_x_matches = re.findall(r'(+(d+))', block)
if plus_x_matches:
# Convert the found matches to integers and find the maximum
max_x = max(map(int, plus_x_matches))
# Replace all `(+x)` with an empty string
block = re.sub(r'(+d+)', '', block)
# Find the position where the maximum `(+x)` was found
max_x_position = block.rfind(f'(+{max_x})')
# If `(+x)` was found, insert `[col 4]` before the text
if max_x_position != -1:
# Insert `[col 4]` at the position of the max `(+x)`
block = block[:max_x_position] + '[col 4]' + block[max_x_position:]
return block
def main():
# Read input file
with open('input.msg', 'r') as infile:
content = infile.read()
# Split the content into blocks
blocks = re.split(r'([sel .+? top])', content)
# Process each block
result = []
in_block = False
current_block = ''
for part in blocks:
if part.startswith('[sel'):
# If there's a previous block to process, do so
if in_block:
result.append(process_block(current_block))
current_block = ''
# Start a new block
result.append(part)
in_block = True
elif in_block:
# Append to the current block content
current_block += part
# Don't forget to process the last block
if in_block:
result.append(process_block(current_block))
# Write output file
with open('output.msg', 'w') as outfile:
outfile.write(''.join(result))
if __name__ == '__main__':
main()
</code>
<code>import re def process_block(block): # Find all instances of `(+x)` and their positions in the block plus_x_matches = re.findall(r'(+(d+))', block) if plus_x_matches: # Convert the found matches to integers and find the maximum max_x = max(map(int, plus_x_matches)) # Replace all `(+x)` with an empty string block = re.sub(r'(+d+)', '', block) # Find the position where the maximum `(+x)` was found max_x_position = block.rfind(f'(+{max_x})') # If `(+x)` was found, insert `[col 4]` before the text if max_x_position != -1: # Insert `[col 4]` at the position of the max `(+x)` block = block[:max_x_position] + '[col 4]' + block[max_x_position:] return block def main(): # Read input file with open('input.msg', 'r') as infile: content = infile.read() # Split the content into blocks blocks = re.split(r'([sel .+? top])', content) # Process each block result = [] in_block = False current_block = '' for part in blocks: if part.startswith('[sel'): # If there's a previous block to process, do so if in_block: result.append(process_block(current_block)) current_block = '' # Start a new block result.append(part) in_block = True elif in_block: # Append to the current block content current_block += part # Don't forget to process the last block if in_block: result.append(process_block(current_block)) # Write output file with open('output.msg', 'w') as outfile: outfile.write(''.join(result)) if __name__ == '__main__': main() </code>
import re


def process_block(block):
    # Find all instances of `(+x)` and their positions in the block
    plus_x_matches = re.findall(r'(+(d+))', block)
    if plus_x_matches:
        # Convert the found matches to integers and find the maximum
        max_x = max(map(int, plus_x_matches))
        # Replace all `(+x)` with an empty string
        block = re.sub(r'(+d+)', '', block)
        # Find the position where the maximum `(+x)` was found
        max_x_position = block.rfind(f'(+{max_x})')
        # If `(+x)` was found, insert `[col 4]` before the text
        if max_x_position != -1:
            # Insert `[col 4]` at the position of the max `(+x)`
            block = block[:max_x_position] + '[col 4]' + block[max_x_position:]
    return block


def main():
    # Read input file
    with open('input.msg', 'r') as infile:
        content = infile.read()

    # Split the content into blocks
    blocks = re.split(r'([sel .+? top])', content)

    # Process each block
    result = []
    in_block = False
    current_block = ''
    for part in blocks:
        if part.startswith('[sel'):
            # If there's a previous block to process, do so
            if in_block:
                result.append(process_block(current_block))
                current_block = ''
            # Start a new block
            result.append(part)
            in_block = True
        elif in_block:
            # Append to the current block content
            current_block += part

    # Don't forget to process the last block
    if in_block:
        result.append(process_block(current_block))

    # Write output file
    with open('output.msg', 'w') as outfile:
        outfile.write(''.join(result))


if __name__ == '__main__':
    main()

New contributor

Medusa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật