Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert js regex into python regex

I'm working on a part of a project, which is repleacing http url's with https url's if possible.

The Problem is, that the regular expressions for that are written for the javascript regex parser, but I'm using that regex inside python. To be compatible, I would rewrite the regex during parsing into a valide python regex.

as example, I have that regular expression given:

https://$1wikimediafoundation.org/

and I would a regular expression like that:

https://\1wikimediafoundation.org/

my problem is that I doesn't know how to do that (converting $ into \)


This code doesn't work:

'https://$1wikimediafoundation.org/'.replace('$', '\')

generate the following error:

SyntaxError: EOL while scanning string literal

This code work without error:

'https://$1wikimediafoundation.org/'.replace('$', '\\')

but generate a wrong output:

'https://\\1wikimediafoundation.org/'
like image 638
pointhi Avatar asked Sep 12 '25 22:09

pointhi


1 Answers

You test your regex here https://regex101.com/, and then change it to python. Additionaly, to replace the matched group, you can use re.sub module on these lines:

re.sub(r"'([^']*)'", r'{\1}', col ) ) replace

'Protein_Expectation_Value_Log(e)', 'Protein_Intensity_Log(I)'

{Protein_Expectation_Value_Log(e)}, {Protein_Intensity_Log(I)}

More you can refer here

like image 187
Anu Avatar answered Sep 15 '25 11:09

Anu