Search a delimited string in a file - Python
Question: I have the following read.json file

    
    
    {:{"JOL":"EuXaqHIbfEDyvph%2BMHPdCOJWMDPD%2BGG2xf0u0mP9Vb4YMFr6v5TJzWlSqq6VL0hXy07VDkWHHcq3At0SKVUrRA7shgTvmKVbjhEazRqHpvs%3D-%1E2D%TL/xs23EWsc40fWD.tr","LAPTOP":"error"}
    

and python script :

    
    
    import re
    
    shakes = open("read.json", "r")
    needed = open("needed.txt", "w")
    for text in shakes:
        if re.search('JOL":"(.+?).tr', text):
             print >> needed, text,
    

I want it to find what's between two words (JOL":" and .tr) and then print it.
But all it does is printing all the text set in "read.json".


Answer: You're calling `re.search`, but you're not doing anything with the returned
match, except to check that there is one. Instead, you're just printing out
the original `text`. So of course you get the whole line.

The solution is simple: just store the result of `re.search` in a variable, so
you can use it. For example:

    
    
    for text in shakes:
        match = re.search('JOL":"(.+?).tr', text)
        if match:
            print >> needed, match.group(1)
    

In your example, the match is
`JOL":"EuXaqHIbfEDyvph%2BMHPdCOJWMDPD%2BGG2xf0u0mP9Vb4YMFr6v5TJzWlSqq6VL0hXy07VDkWHHcq3At0SKVUrRA7shgTvmKVbjhEazRqHpvs%3D-%1E2D%TL/xs23EWsc40fWD.tr`,
and the first (and only) group in it is
`EuXaqHIbfEDyvph%2BMHPdCOJWMDPD%2BGG2xf0u0mP9Vb4YMFr6v5TJzWlSqq6VL0hXy07VDkWHHcq3At0SKVUrRA7shgTvmKVbjhEazRqHpvs%3D-%1E2D%TL/xs23EWsc40fWD`,
which is (I think) what you're looking for.

However, a couple of side notes:

First, `.` is a special pattern in a regex, so you're actually matching
anything up to _any character_ followed by `tr`, not `.tr`. For that, escape
the `.` with a `\`. (And, once you start putting backslashes into a regex, use
a raw string literal.) So: `r'JOL":"(.+?)\.tr'`.

Second, this is making a lot of assumptions about the data that probably
aren't warranted. What you really want here is not "everything between
`JOL":"` and `.tr`", it's "the value associated with key `'JOL'` in the JSON
object". The only problem is that this isn't quite a JSON object, because of
that prefixed `:`. Hopefully you know where you got the data from, and
therefore what format it's actually in. For example, if you know it's actually
a sequence of colon-prefixed JSON objects, the right way to parse it is:

    
    
    d = json.loads(text[1:])
    if 'JOL' in d:
        print >> needed, d['JOL']
    

Finally, you don't actually have anything named `needed` in your code; you
opened a file named `'needed.txt'`, but you called the file object `love`. If
your real code has a similar bug, it's possible that you're overwriting some
completely different file over and over, and then looking in `needed.txt` and
seeing nothing changed each time…

