user3107977
user3107977

Reputation: 43

inserting variable into regular expression

I am trying to write code that can extract values from variables in a text file.

so if the file was
"bob= 1255 mike = 13"

when I specified bob as var_name it would extract 1255, and so on.

based my code off of this but it doesnt seem to be working

var_name = 'bob'

regexp = re.compile(r''+var_name+'.*?([0-9.-]+)')

with open("textfile") as s:
    for line in s:
        match = regexp.match(line)
        if match:
            print(match.group(1))

var_name = 'mike'

regexp = re.compile(r''+var_name+'.*?([0-9.-]+)')

with open("textfile") as s:
    for line in s:
        match = regexp.match(line)
        if match:
            print(match.group(1))

Upvotes: 0

Views: 68

Answers (2)

Amadan
Amadan

Reputation: 198324

You are using re.match, which only finds things at the start of the string (and mike is not at the start of the string). Use re.search, which finds things at any position.


Slightly off-topic: Note that r'...' does not mean "regexp literal". It means "raw string literal". The purpose of it is to avoid having to escape backslashes inside the string. Now, '' very obviously does not contain any backslashes, so r'' is not at all different from ''. On the other hand, .*?([0-9.-]+) is complex enough that we are not sure whether or not there are (or will be) any backslashes in it - and yet you don't make it into a raw string literal. Puzzling. :) I would have written var_name + r'.*?([0-9.-]+)', without the useless r'' +...

Upvotes: 1

virolino
virolino

Reputation: 2201

You did not mention what does work / what does not work.

Instead of .*? you should use \s*=\s*. Otherwise you can catch things like #edsakjj*kjn - and I assume you do not want this.

You may also make sure that the number is really a number: -?\d+(\.?\d+)?: optional - (minus, for negative numbers), mandatory digit(s), optionally: decimal mark followed by digit(s).

Test regex

Regarding python code, I am not your guy, sorry :(

Upvotes: 0

Related Questions