0

i have to read a line in which i looking for pattern like

width:40
height :50
left : 60
right: 70

following found the required pattern

line = "width:40"
match = re.search(r'width\s*:\s*\d+', line)

in above code i have hard-coded the regex pattern for width

i have stored all four variables in array key_word = ['width', 'height', 'left', 'right']

i want to search for pattern for all these variable like

for key in key_word:
        match = re.search(key, line)

the problem is how can i make this key a raw string which will be a pattern like

r'width\s*:\s*\d+'
r'height\s*:\s*\d+'
r'left\s*:\s*\d+'
r'right\s*:\s*\d+'

4 Answers 4

2

I would do something like the following:

key_word = ['width', 'height', 'left', 'right']
regex_template = r'{}\s*:\s*\d+'
for key in key_word:
    print re.search(regex_template.format(key), line)
Sign up to request clarification or add additional context in comments.

Comments

1

You can also just use a generic regex:

matches = re.findall(r'(.*?)\s*:\s*(\d+)', text)

matches will be a list of (key, value) tuples.

Comments

0

Why not use split (or partition) and strip?

for line in lines:
    key, sep, value = line.partition(':')
    key = key.strip()
    value = value.strip()

If you're really needing to use regular expressions, you can format them, too:

r'%s\s*:\s*\d+' % 'width'

Or for each key:

regexes = [r'%s\s*:\s*\d+' % key for key in ['width', 'height', ...]]

Comments

0

You don't need regular expressions for this task. See other answers.

However if you insist, you can create one dynamically using re.escape:

import re

key_word = ['width', 'height', 'left', 'right']

myre = r'({})\s*:\s*(\d+)'.format('|'.join(map(re.escape, key_word)))

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.