#!/usr/bin/python2
'''usage: rex [-h] [-v] pattern replacement [string]

rex 0.2.1 replace string using python re.sub

positional arguments:
  pattern        python regular expression
  replacement    string replacement (\1 \2 .. for matches
  string         string to replace. default from stdin

optional arguments:
  -h, --help     show this help message and exit
  -v, --version  show program's version number and exit

Eg:  echo 'This test' | rex '^[Tt]?his (.+)' '\1'
     > test'''

from loadconfig import Config, set_verprog
import re
import sys

conf = '''\
    version: 0.2.1
    clg:
        description: $prog $version replace string using python re.sub
        epilog: |
            Eg:  echo 'This test' | rex '^[Tt]?his (.+)' '\\1'
                 > test
        options:
            version:
                short: v
                action: version
                version: $prog $version
        args:
            pattern:
                help: python regular expression
            replacement:
                help: string replacement (\\1 \\2 .. for matches
            string:
                nargs: '?'
                default: ''
                help: string to replace. default from stdin'''


def rex(pattern, replacement, string=''):
    '''Match stdin or string
    >>> rex('^[Tt]?his (.+)', '\1', 'This test')
    test

    $ echo 'This test' | rex '^[Tt]?his (.+)' '\1'
    test
    '''
    if string == '':
        string = sys.stdin.read()
    st = 0 if re.search(pattern, string) else 1
    ret = re.sub(pattern, replacement, string) if st == 0 else ''
    return (ret, st)


def main(args):
    config = set_verprog(conf)
    c = Config(config, args=sys.argv)
    ret, st = rex(c.pattern, c.replacement, c.string)
    sys.stdout.write(ret)
    sys.exit(st)


if __name__ == '__main__':
    main(sys.argv)
