Improve replace

Signed-off-by: Rémi BERTHO <remi.bertho@dalan.fr>
This commit is contained in:
Rémi BERTHO 2017-10-13 18:48:50 +02:00
parent 51b4b0f5ee
commit b46281ffb8
Signed by: dalan
GPG Key ID: EE3B917931C07B64
1 changed files with 7 additions and 3 deletions

10
SSnR.py
View File

@ -34,6 +34,8 @@ def main():
parser.add_argument('-e', '--regex', help='Regex', required=True) parser.add_argument('-e', '--regex', help='Regex', required=True)
parser.add_argument('-s', '--string', help='String', required=True) parser.add_argument('-s', '--string', help='String', required=True)
parser.add_argument('-r', '--replace', help='Replace', required=False) parser.add_argument('-r', '--replace', help='Replace', required=False)
parser.add_argument('-m', '--print_nb_match', help='Print the number of match in replace',
required=False, action='store_true')
args = vars(parser.parse_args()) args = vars(parser.parse_args())
# Compile regex # Compile regex
@ -47,7 +49,7 @@ def main():
return -1 return -1
if args["replace"] is not None: if args["replace"] is not None:
replace(ex, args["string"], args["replace"]) replace(ex, args["string"], args["replace"], args["print_nb_match"])
else: else:
search(ex, args["string"]) search(ex, args["string"])
return 0 return 0
@ -78,15 +80,17 @@ def search(ex, string):
print("Number of match: " + str(nb_match)) print("Number of match: " + str(nb_match))
def replace(ex, string, replace_string): def replace(ex, string, replace_string, print_nb):
""" """
Replace in a string Replace in a string
:param ex: Regular expression :param ex: Regular expression
:param string: A string :param string: A string
:param print_nb: Print the number of match
""" """
res = ex.subn(replace_string, string) res = ex.subn(replace_string, string)
print(res[0]) print(res[0])
print("Number of match: " + str(res[1])) if print_nb:
print("Number of match: " + str(res[1]))
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())