Regex Substitution Between Two Expressions
So lets say I have the following strings: stringX = ['187-49481,14', '181-457216', '196,61-04-22', '1972-10-28', '19,940-04-16', '2017-08,8-29', '2014-04-18'] Notice that I have t
Solution 1:
Solution
You could use a simple pythonic list-comprehension with str.replace()
.
[x.replace(',','') for x in stringX]
Output:
['187-4948114',
'181-457216',
'19661-04-22',
'1972-10-28',
'19940-04-16',
'2017-088-29',
'2014-04-18']
If you want to use regex
, then this could be an alternative.
import re # regex library
re.sub(',','', '|'.join(stringX)).split('|')
Output:
['187-4948114',
'181-457216',
'19661-04-22',
'1972-10-28',
'19940-04-16',
'2017-088-29',
'2014-04-18']
Extracting Single-Dashed and Double-Dashed Values
You could extract the numbers with single and double dashes as follows using re.findall()
.
import re # regex library
text = [x.replace(',','') for x in stringX]
text = '\n'.join(text)
single_dash = re.findall('\d+-\d+', text)
double_dash = re.findall('\d+-\d+-\d+', text)
print(f'single dash: \n\n{single_dash}\n')
print(f'double dash: \n\n{double_dash}\n')
Output:
single dash:
['187-4948114', '181-457216', '19661-04', '1972-10', '19940-04', '2017-088', '2014-04']
double dash:
['19661-04-22', '1972-10-28', '19940-04-16', '2017-088-29', '2014-04-18']
Solution 2:
You can use your regex approach by using a lambda expression in re.sub
Change
re.sub(r'\d+\-\d+(\,)\d+', '', stringX)
To:
re.sub(r'\d+\-\d+(\,)\d+', lambda m: m.group(0).replace(',', ''), stringX)
Solution 3:
You don't need regex for it, you can just split string at ','. And if it yields an array with length of more than 1, chop last index of left string (at index 0) and first of right (at index 1). Oh may be you do need it, idk.
const p = '187-49481,14';
const regex = /\d,/;
console.log(p.replace(regex, ''));//result is 187-494814
This is done in JavaScript but should be as easy with Python match \d,
and replace it with nothing. Easy peasy,
I don't know Python that well but that, probably, would do it
re.sub(r'\d,', '', stringX)
Solution 4:
import re
[re.sub(r'\,', '', x) for x in stringX]
['187-4948114', '181-457216', '19661-04-22', '1972-10-28', '19940-04-16', '2017-088-29', '2014-04-18']
Post a Comment for "Regex Substitution Between Two Expressions"