Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are there different regex results in javascript and python?

I am trying to match 5 letter words that have ‘a’ as the second character, followed by two double letters. e.g. ‘bally’

I’m using regex (so now have 2 problems).

In python, this is not matching:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import re
caxxy = re.compile('^[a-z]a([a-z])\1y')
print (caxxy.match('bally')) #None

However, in javascript, this is matching:

const word = 'bally';
const caxxy = /^[a-z]a([a-z])\1y/;
const match = word.match(caxxy);
console.log(match); // > Array ["bally", "l"]

Why is the same string and regex returning different results in python and js?

>Solution :

It has nothing to do with different programming languages. It’s a difference between a RegExp literal and a string.

'^[a-z]a([a-z])\1y'

is a string containing

^[a-z]a([a-z])1y

The strings

'\1'

and

'1'

are similar. It’s explained here.
You have to escape the backslash with

'^[a-z]a([a-z])\\1y'

or use raw strings

r'^[a-z]a([a-z])\1y'

On the other side,

/^[a-z]a([a-z])\1y/

isn’t a string. It’s a RegExp literal. You don’t have to escape the backslash.

You have the same behavior in JavaScript using strings:

const word = 'bally';
let caxxy = new RegExp('^[a-z]a([a-z])\1y');
let match = word.match(caxxy);
console.log(match);
caxxy = new RegExp('^[a-z]a([a-z])\\1y');
match = word.match(caxxy);
console.log(match);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading