Ison
Ison

Reputation: 403

Convert js function with regex to python one

I got a basic function written in js that takes some substring and matches via regex variations of the substring stored in array.

const arr = ['autoencoder', 'auto-encoder', 'auto encoder', 'auto', 'one'];
const arr2 = ['autoencoder', 'one'];

const fn = (s, a) => a.includes(s.replace(/\W/g, ''));

console.log(fn('autoencoder', arr)); 
console.log(fn('auto encoder', arr));
console.log(fn('auto-encoder', arr)); 

console.log(fn('autoencoder', arr2)); 
console.log(fn('auto encoder', arr2)); 
console.log(fn('auto-encoder', arr2));

The problem is that I cannot reproduce it in Python

I tried to reproduce it in this way:  

import re
a = ['autoencoder', 'auto-encoder', 'auto encoder', 'auto', 'one']
b = 'autoencoder'

def t(w, a):
  return [s for s in a if re.match(r'\W\ g', w)]

print(t('autoencoder',a)) 

But obviously I did not succeed as basically it returns empty list

Upvotes: 0

Views: 123

Answers (1)

user459872
user459872

Reputation: 24602

Your JavaScript function does the following

const fn = (s, a) => a.includes(s.replace(/\W/g, ''));
  • Replace all non word characters with empty string s.replace(/\W/g, '')
  • Then a.includes determines whether the array(a in this case) includes this value, returning true or false

To replicate this in python you can do the following

>>> import re
>>> def fn(s, a):
...     return re.sub(r'\W', '', s) in a # re.sub(r'\W', '', s) replace all non word characters with empty string

Upvotes: 2

Related Questions