SSnR/SSnR.py

93 lines
2.4 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# SSnR.py
#
# Copyright 2017 Rémi BERTHO <remi.bertho@dalan.fr>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
import sys
import argparse
import regex
def main():
"""
Main function
"""
parser = argparse.ArgumentParser(description='Search and replace tool', prog='SSnR')
parser.add_argument('-e', '--regex', help='Regex', required=True)
parser.add_argument('-s', '--string', help='String', required=True)
parser.add_argument('-r', '--replace', help='Replace', required=False)
args = vars(parser.parse_args())
# Compile regex
try:
ex = compile_regex(args["regex"])
except SyntaxError as exception:
print("Error when compiling regex: " + str(exception))
return -1
except regex.error as exception:
print("Error when compiling regex: " + exception.msg)
return -1
if args["replace"] is not None:
replace(ex, args["string"], args["replace"])
else:
search(ex, args["string"])
return 0
def compile_regex(ex):
"""
Compile regex
:param ex: Regular expression
"""
regex_compile = regex.compile(ex, regex.MULTILINE)
if regex_compile is None:
raise SyntaxError('Error in the regex')
else:
return regex_compile
def search(ex, string):
"""
Search in a string
:param ex: Regular expression
:param string: A string
"""
ite = ex.finditer(string)
nb_match = 0
for match in ite:
nb_match += 1
print(" - Found \"" + match.group(0) + "\" at [" + str(match.start(0)) +
":" + str(match.end(0)) + "]")
print("Number of match: " + str(nb_match))
def replace(ex, string, replace_string):
"""
Replace in a string
:param ex: Regular expression
:param string: A string
"""
res = ex.subn(replace_string, string)
print(res[0])
print("Number of match: " + str(res[1]))
if __name__ == '__main__':
sys.exit(main())