#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import re import sys def main(): pattern, repl, string, count = parse_args() # https://docs.python.org/3/library/re.html#re.MULTILINE # re.MULTILINE # When specified, the pattern character '^' matches at the beginning of the string # and at the beginning of each line (immediately following each newline); # and the pattern character '$' matches at the end of the string # and at the end of each line (immediately preceding each newline). # https://docs.python.org/3/library/re.html#re.findall # Return all non-overlapping matches of pattern in string, as a list of strings or tuples. # The string is scanned left-to-right, and matches are returned in the order found. matches = re.findall(pattern, string, flags=re.MULTILINE) if len(matches) != count: print(f'[ERROR] Expected {count} matches of pattern in string, but got {len(matches)}.') exit(1) # https://docs.python.org/3/library/re.html#re.sub # Return the string obtained by replacing the leftmost non-overlapping occurrences of `pattern` # in `string` by the replacement `repl`. string = re.sub(pattern, repl, string, flags=re.MULTILINE) print(string, end='') def parse_args(): parser = argparse.ArgumentParser(prog='py-regex-replace') parser.add_argument('--pattern', '-p', help='regex search pattern', required=True, type=str) parser.add_argument('--repl', '-r', help='replacement', required=True, type=str) parser.add_argument('--count', '-c', help='expected count of pattern in string', default=1, type=int) args = parser.parse_args() string = sys.stdin.read() if len(string) == 0: print('[WARNING] The given string is empty.', file=sys.stderr) return args.pattern, args.repl, string, args.count if __name__ == '__main__': main()