0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

a = ['auto-encoder', 'auto encoder', 'auto', 'one'] b = ['autoencoder', 'one'] def fn(s, a): return re.sub(r'\W', '', s) in a print(fn('autoencoder', a)) In such a case the python code will return False, while js will return True
@Ison I am getting False in both cases. Would you please make sure that the array(a) is ['auto-encoder', 'auto encoder', 'auto', 'one'] in both python and Javascript
Hmm, you're right, my fault. Oh God, I was so happy finally dealing with regex to be able match different forms of some string, but no -_-

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.