remove everything between different characters python
Question:
My input is the below code.
re.sub(r'-c.*?csv', '', '-c dir/dir/dir/file.csv')
The output I am expecting is to only have
'-c csv'
I know I am missing something with this regex to get only the -c and csv in the output string. Any help would be greatly appreciated on this.
Answers:
You could try:
re.sub(r'(-c)(.*?)(csv)', r'1 3', '-c dir/dir/dir/file.csv')
.
You are effectively replacing the -c
, the characters in between, as well as csv
in your regex.
If you want to keep parts of it, surround them with parentheses and use their numbers in the replacement to keep what you want and discard what you don’t.
I’m a bit confused about your use case, but I hope this serves the purpose you’ve got in mind.
A useful resource: https://www.pythontutorial.net/python-regex/python-regex-sub/
My input is the below code.
re.sub(r'-c.*?csv', '', '-c dir/dir/dir/file.csv')
The output I am expecting is to only have
'-c csv'
I know I am missing something with this regex to get only the -c and csv in the output string. Any help would be greatly appreciated on this.
You could try:
re.sub(r'(-c)(.*?)(csv)', r'1 3', '-c dir/dir/dir/file.csv')
.
You are effectively replacing the -c
, the characters in between, as well as csv
in your regex.
If you want to keep parts of it, surround them with parentheses and use their numbers in the replacement to keep what you want and discard what you don’t.
I’m a bit confused about your use case, but I hope this serves the purpose you’ve got in mind.
A useful resource: https://www.pythontutorial.net/python-regex/python-regex-sub/