Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Replace All But Pattern

This might be a duplicate, but I'm trying to replace all but a certain string pattern. Here is a sample of strings:

'dkas;6-17'
'dsajdl 10'
'dsjalkdj16-20'

The goal here is to replace anything that is not numbers-numbers with nothing. So what I'd get from the strings above are:

'6-17'
''
'16-20'

The second string would yield nothing because it didn't match the pattern. I know the regular expression to match my pattern, but I'm confused about how I'd use regexp_replace to match all but that pattern. The following is what I have, but this replaces the pattern I want to actually keep.

re.sub('[0-9]{1,2}\-[0-9]{1,2}', '', text)
like image 370
ben890 Avatar asked Aug 13 '26 23:08

ben890


1 Answers

If you mean by the second would yield nothing, you could match any char except a digit or newline, followed by capturing the pattern in a group.

If the sub should leave an empty string, you could match the whole line using an alternation.

[^\d\r\n]+(\d{1,2}-\d{1,2})|.+

In parts

  • [^\d\r\n]+ Match 1+ times any char except a digit or a newline
  • (\d{1,2}-\d{1,2}) Capture group 1, match 1-2 digits, - and 1-2 digits
  • | Or
  • .+ Match any char except a newline 1+ more times

Regex demo | Python demo

Example code

import re

lines = [
    'dkas;6-17',
    'dsajdl 10',
    'dsjalkdj16-20'
]

for text in lines:
    print(re.sub('[^\d\r\n]+(\d{1,2}-\d{1,2})|.+', r'\1', text))

Output

6-17

16-20
like image 108
The fourth bird Avatar answered Aug 16 '26 13:08

The fourth bird