Using sets to eliminate duplicates:
#!/usr/bin/python
import re
pattern = re.compile("[^/]*\.js")
matches = set()
with open('access_log.txt') as f:
for line in f:
for match in re.findall(pattern, line):
#x = str(match) # or just use match
if match not in in matches:
print match
matches.add(match)
But I question your regex:
You are doing a findall on each line, which suggests that each line might have multiple "hits", such as:
file1.js file2.js file3.js
But in your regex:
[^/]*\.js
[^/]* is doing a greedy match and would return only one match, namely the complete line.
If you made the match non-greedy, i.e. [^/]*?, then you would get 3 matches:
'file1.js'
' file2.js'
' file3.js'
But that highlights another potential problem. Do you really want those spaces in the second and third matches for these particular cases? Perhaps in the case of /abc/ def.js you would keep the leading blank that follows /abc/.
So I would suggest:
#!/usr/bin/python
import re
pattern = re.compile("""
(?x) # verbose mode
(?: # first alternative:
(?<=/) # positive lookbehind assertion: preceded by '/'
[^/]*? # matches non-greedily 0 or more non-'/'
| # second alternative
(?<!/) # negative lookbehind assertion: not preceded by '/'
[^/\s]*? # matches non-greedily 0 or more non-'/' or non-whitespace
)
\.js # matches '.js'
""")
matches = set()
with open('access_log.txt') as f:
for line in f:
for match in pattern.findall(line):
if match not in matches:
print match
matches.add(match)
If the filename cannot have any whitespace, then just use:
pattern = re.compile("[^\s/]*?\.js")
with open(...)pattern -- this ensures the file is closed when you're done with it, even if an error occurs.