1

I use re to find a word on a file and I stored it as lattice_type Now I want to use the word stored on lattice_type to make another regex

I tried using the name of the variable on this way

pnt_grp=re.match(r'+ lattice_type + (.*?) .*',line, re.M|re.I)

Here I look for the regex lattice_type= and store the group(1) in lattice_type

latt=open(cell_file,"r")
    for types in latt:
        line = types
        latt_type = re.match(r'lattice_type = (.*)', line, re.M|re.I)
        if latt_type:
            lattice_type=latt_type.group(1)

Here is where I want to use the variable containing the word to find it on another file, but I got problems

pg=open(parameters,"r")
    for lines in pg:
        line=lines
        pnt_grp=re.match(r'+ lattice_type + (.*?) .*',line, re.M|re.I)
        if pnt_grp:
            print(pnt_grp(1))
Michael
  • 1,063
  • 14
  • 32

1 Answers1

3

The r prefix is only needed when defining a string with a lot of backslashes, because both regex and Python string syntax attach meaning to backslashes. r'..' is just an alternative syntax that makes it easier to work with regex patterns. You don't have to use r'..' raw string literals. See The backslash plague in the Python regex howto for more information.

All that means that you certainly don't need to use the r prefix when already have a string value. A regex pattern is just a string value, and you can just use normal string formatting or concatenation techniques:

pnt_grp = re.match(lattice_type + '(.*?) .*', line, re.M|re.I)

I didn't use r in the string literal above, because there are no \ backslashes in the expression there to cause issues.

You may need to use the re.escape() function on your lattice_type value, if there is a possibility of that value containing regular expression meta-characters such as . or ? or [, etc. re.escape() escapes such metacharacters so that only literal text is matched:

pnt_grp = re.match(re.escape(lattice_type) + '(.*?) .*', line, re.M|re.I)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I make the change but I obtain this: at '_sre.SRE_Match' object is not callable because lattice_type is the match of tha later searching. How can I fix that? – Jorge Castro Jan 23 '19 at 17:04
  • @JorgeCastro: if `lattice_type` is a match object, then use a [match object method](https://docs.python.org/3/library/re.html#match-objects) to get a string. Such as `lattice_type.group()`. – Martijn Pieters Jan 23 '19 at 17:08