0

I have this Python code, I want to map the array of regex strings, to compiled regexes, and I need to create a function that checks to see if a certain line of texts matches all the given regular expressions. But I suck at Python and only know JS and Java.

#sys.argv[2] is a JSON stringified array

regexes = json.loads(sys.argv[2]);

#need to call this for each regex in regexes
pattern = re.compile(regex)

def matchesAll(line):
    return True if all line of text matches all regular expressions

In JS, what I want looks like:

// process.argv[2] is a JSON stringified array
var regexes = JSON.parse(process.argv[2])
                 .map(v => new RegExp(v))

function matchesAll(line){
     return regexes.every(r => r.test(line));
 }

Can somehow help me translate? I was reading about how to do mapping of arrays with Python and I was like huh?

3 Answers 3

2

To compile all expressions you can simply use

patterns = map(re.compile, regexs)

and to do the check:

def matchesAll(line):
    return all(re.match(x, line) for x in patterns)
Sign up to request clarification or add additional context in comments.

2 Comments

do I have to "import all"?
@AlexanderMills No. It's builtin function.
1

You can try something like this:

regexes = [re.compile(x) for x in json.loads(sys.argv[2])]

def matchesAll(line):
    return all([re.match(x, line) for x in regexes])

Test Example:

import re

regexes = [re.compile(x) for x in ['.*?a.*','.*?o.*','.*r?.*']]

def matchesAll(line):
    return all([re.match(x, line) for x in regexes])

print matchesAll('Hello World aaa')
print matchesAll('aaaaaaa')

Output:

True
False

1 Comment

thanks, I will move on to this, I will post an answer of what I have
0

This is what I have, I hope it's right

regex = json.loads(sys.argv[2]);

regexes=[]

for r in regex:
    regexes.append(re.compile(r))

def matchesAll(line):
    for r in regexes:
        if not r.search(line):
            return False
    return True

I will try @MYGz's answer, the lambda syntax is pretty foreign to me.

Comments

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.