You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python正则或文本替换简化PL/1代码中的多条件IF语句?

Simplifying Verbose PL/1 IF Conditions with Python

Absolutely! I’ve tackled similar PL/1 code cleanup tasks before, and Python’s regex and string processing tools are perfect for automating this kind of repetitive simplification. Here’s a practical, tested solution to turn those clunky OR’d conditions into clean in() checks:

Step-by-Step Solution

First, we’ll use a combination of regex matching and a custom callback function to group conditions by variable, then rewrite them in the var in ('val1','val2') format.

Python Code Implementation

import re

def simplify_pl1_if(match):
    # Extract the core conditions from the IF statement
    raw_conditions = match.group(1)
    
    # Split conditions by the OR operator, stripping extra whitespace
    condition_parts = [part.strip() for part in raw_conditions.split('|')]
    
    # Group conditions by their variable name
    variable_groups = {}
    unprocessed_conditions = []
    
    for cond in condition_parts:
        # Match patterns like "cond == 'A'" or "cond_ex=='B_EX'"
        var_value_match = re.match(r'(\w+)\s*==\s*\'([^\']+)\'', cond)
        if var_value_match:
            var_name = var_value_match.group(1)
            value = var_value_match.group(2)
            
            # Build a list of values for each variable
            if var_name not in variable_groups:
                variable_groups[var_name] = []
            variable_groups[var_name].append(value)
        else:
            # Keep any non-matching conditions (e.g., cond > 10) as-is
            unprocessed_conditions.append(cond)
    
    # Construct the simplified condition parts
    simplified_segments = []
    for var, values in variable_groups.items():
        joined_values = "','".join(values)
        simplified_segments.append(f"{var} in ('{joined_values}')")
    
    # Add back any unprocessed conditions
    simplified_segments.extend(unprocessed_conditions)
    
    # Reassemble the full IF statement
    return f"if {' | '.join(simplified_segments)} then;"

# Test with your example
original_line = "if cond == 'A' | cond == 'B' | cond == 'C' | cond_ex == 'A_EX' | cond == 'D' | cond_ex == 'B_EX' then;"
simplified_line = re.sub(r'if\s+(.*?)\s+then;', simplify_pl1_if, original_line)

print(simplified_line)
# Output: if cond in ('A','B','C','D') | cond_ex in ('A_EX','B_EX') then;

How It Works

  1. Regex Matching: The outer re.sub targets the entire IF statement, capturing everything between if and then; for processing.
  2. Condition Splitting: We split the captured conditions using | as the delimiter, cleaning up extra whitespace along the way.
  3. Grouping by Variable: For each condition, we check if it follows the var == 'value' pattern. If so, we group all values under their corresponding variable.
  4. Simplification: We convert each variable’s value list into a single var in ('val1','val2') expression.
  5. Handling Edge Cases: Any conditions that don’t fit the pattern (like numeric comparisons or complex expressions) are preserved in their original form.

Batch Processing PL/1 Files

To apply this to an entire PL/1 source file, just read the file line by line, process each line, and write the output to a new file:

with open("old_source.pl1", "r") as infile, open("clean_source.pl1", "w") as outfile:
    for line in infile:
        # Apply the simplification to lines containing IF statements
        processed_line = re.sub(r'if\s+(.*?)\s+then;', simplify_pl1_if, line)
        outfile.write(processed_line)

Notes for Adjustments

  • Quotation Marks: If your PL/1 code uses double quotes instead of single quotes, modify the regex to use " instead of '.
  • Logical ANDs: If you need to handle & operators too, you’ll need to adjust the splitting logic (this solution focuses on | as per your example).
  • Case Sensitivity: PL/1 is case-insensitive for keywords, but variables are case-sensitive. The regex respects variable case as written.

内容的提问来源于stack exchange,提问作者Tae Young Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:33:46