0

This is sample code.

int myCodeVersion = 100;

My .py code as below.

fp = open(path, 'r').read()
myCodeVer = ''.join(map(str, re.findall('myCodeVersion'+ '\s=\s(.*?) ', fp))) 
print 'My Code version: ' + myCodeVer

This is result of my .py code

My Code version: 100;

I want to print only digit as below.

My Code version: 100

How can I fix the my regex?

4 Answers 4

2
myCodeVer = ''.join(map(str, re.findall('myCodeVersion'+ '\s=\s(\d*)', fp))) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thx. But remove white space
re.findall('myCodeVersion\s*=\s*(\d+)', fp)[0] is enough. In fact, \d* is wrong, must be at least \d+.
2

With that particular file you can do it like so:

import re

with open(file, 'r') as f:
    myCodeVer = re.findall('(?<=myCodeVersion)(?:\s*=\s*)(\d+)', f.read())
    print 'My Code version: ' + myCodeVer[0]

Output:

My Code version: 100

Regex:

(?<=myCodeVersion) - Positive look behind of myCodeVersion

(?:\s*=\s*) - Non capturing group, 0 or more spaces on either side of =

(\d+) - Capture 1 or more digits

Comments

0

A slightly more generic approach will be to to capture groups. For example, we can capture variable type, name and value as groups using the pattern-matcher as follows:

s = 'int myCodeVersion = 100;'
import re
# compile the regex pattern, if you need to use multiple times, it will be faster
pattern = re.compile(r"(int|float|double)\s+([A-Za-z][A-Za-z0-9_]+)\s*=\s*(\d+)\s*;") 
m = re.match(pattern, s)
print 'var type: ' + m.group(1)
print 'var name: ' + m.group(2)
print 'var value: ' + m.group(3)
#var type: int
#var name: myCodeVersion 
#var value: 100

For the specific case you are interested in the code can be simplified to the following using the same approach:

pattern = re.compile(r"int\s+myCodeVersion\s*=\s*(\d+)\s*;")
print 'My Code version: ' + ''.join(map(str, re.match(pattern, s).group(1))) 
# My Code version: 100

Comments

0

This could work:

.*\s*=\s*(.*?);

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.