Lua pattern to stop when end of line - string

I need to get help for a pattern in Lua stopping to read after a line break.
My code:
function getusers(file)
local list, close = {}
local user, value = string.match(file,"(UserName=)(.*)")
print(value)
f:close()
end
f = assert(io.open('file2.ini', "r"))
local t = f:read("*all")
getusers(t)
--file2.ini--
user=a
UserName=Tom
Password=xyz
UserName=Jane
Output of script using file2.ini:
Tom
Password=xyz
UserName=Jane
How to get the pattern to stop after it reaches the end of line?

You can use the pattern
"(UserName=)(.-)\n"
Note that besides the extra \n, the lazy modifier - is used instead of *.
As #lhf points out, make sure the file ends with a new line. I think you can append a \n to the string manually before matching.

Related

re.MULTILINE flag is interfering with the end of line $ operator

Sorry if this is a duplicate/basic question, I couldn't find any similar questions.
I have the following multiline string
my_txt = """
foo.exe\n
bar.exec\n
abab.exe\n
"""
(The newlines aren't actually written in my code, I put them there for clarity).
I want to match every file that ends with a .exe, (not .exec).
My regex was initially:
my_reg = re.compile(".+[.](?=exe$)")
my_matches = my_reg.finditer(my_txt)
I hoped that it would first find every character, go back until it found the ., and then check if the characters exe and a newline followed.
Only one match was found, and that was:
abab.exe.
I tried to mess around a bit, and changed the first line:
my_reg = re.compile(".+[.](?=exe$)",flags=re.MULTILINE).
This time, it successfully ran, returning
foo.
abab.
I thought re.MULTILINE wasn't supposed to interfere with the $ operator, or am I wrong about the $ operator/misusing something?
Thanks in advance!
You do need the multiline flag, otherwise $ will only match the absolute end of your input. You just need to match exe instead of using a lookahead:
my_reg = re.compile(".+[.]exe$", re.MULTILINE)
Output:
['foo.exe', 'abab.exe']
Demo
If you are trying to match the filename without the extension, you can put the period inside the lookahead:
my_reg = re.compile(r".+(?=\.exe$)", re.MULTILINE)
Output:
['foo', 'abab']
Demo

os.path.exists() always returns false

I am trying to check if a file exits or not in the specified directory. If it is, then I would move the file to another directory. Here is my code
def move(pnin, pno):
if (os.path.exists(pnin)):
shutil.move(pnin, pno)
here is an example of pnin and pno
pnin='D:\\extracted\\extrimg_2016000055202500\\2016000055202500_65500000007006_11_6.png'
pno=D:\folder\discarded
I have a bit more than 8000 input directories. I copied this pnin from the output of print(pnin).When I define pnin externally as in the example, the if statement works. But when I want to run 'move' function iteratively, if statement is never executed. What could be the problem and how can I solve this?
Here is how I call move function:
def clean_Data(inputDir, outDir):
if (len(listf) > 1):
for l in range(1,len(listf)):
fname = hashmd5[m][l]
pathnamein = os.path.join(inputDir, fname)
pathnamein = "%r"%pathnamein
pathnameout = outfile
move(pathnamein, pathnameout)
When I try below code it does not give any output. For loop şs working. When I use print(pathnamein) in the for loop it shows all the values of pathnamein.
def move(pnin, pno):
os.path.exists(pnin)
You should use backslash to escape backslashes in your pno string:
pno='D:\\folder\\discarded'
or use a raw string instead:
pno=r'D:\folder\discarded'
Otherwise \f would be considered a formfeed character.

how to replace multiple duplicate strings in a file without deleting anything else python 3

Ok so I have this code:
for line in fileinput.FileInput("zero.html",inplace=1):
if '{problem}' in line:
rep = 'a dynamic var'
line = line.replace('{problem}', rep)
print(line)
Now, the problem is that it replaces the text fine, but it deletes all other lines without '{problem}' in it. How can I replace '{problem}' with something else, without deleting the other lines? Also, I have multiple occurrences of '{problem}' in my file, and I want each one to be changed to a different, random string.
Thanks!
The if statement doesn't say what to do with the line if it doesn't contain '{problem}'. So as written, your code just ignores those lines. You could add an else clause that prints the line. Or you could just drop the if test, like this:
for line in fileinput.FileInput("zero.html", inplace=1):
rep = 'a dynamic var'
line = line.replace('{problem}', rep)
print(line)
The replace method will leave the line unchanged if it doesn't contain '{problem}'.

Other methods of reading a file without newlines

I'm learning python and was wondering if it's possible to write the below code differently, but have the same function. The purpose of this code is to split \n and remove spaces from the right:
contents = readlines()
stripped_contents = [(element.rstrip()) for element in contents]
You don't need to call readlines if you're going to iterate over the file(?). Also, use better names like "line" instead of "element".
stripped_lines = [line.rstrip() for line in file]
If you're going to use stripped_lines immediately as an iterable and only once, use a generator expression instead.
stripped_lines = (line.rstrip() for line in file)

Lua pattern to match the path

I would like to take a string representing a file path, strip off the file name and save just the path.
For example, if I have:
"/folder1/folder2/file.name"
I would like to end up with "/folder1/folder2/" in my string.
I've been playing around with string.match() as documented here: http://lua-users.org/wiki/StringLibraryTutorial
I have the following code:
mystring = "/var/log/test.log"
print(string.match(mystring, "%/"))
When I run this script, I end up with just a '/' returned.
I was expecting that it would return the positions of the two '/' in the string.
I've also tried replacing the pattern "%/" with just "/" but that gives me the same results.
I'm sure I'm missing something very simple but I can't see what it is.
By the pattern %/ or /, you are telling string.match to look for a string / and that's what you got. Try with this:
local mystring = "/var/log/test.log"
print(string.match(mystring, ".+/"))
Here the pattern .+/ means to look for one or more whatever characters(.) followed by a /. + means it's greedy, i.e, match as long as possible.
Try any this options:
local mystring = "/var/log/test.log"
print(mystring:gsub('([%w+]+%.%w+)$',''))
output: /var/log/
local mystring = "/var/log/test.log"
print(mystring:match('^(/.+/)'))
output: /var/log/
Or too a simple function
function anystring(string)
local string = string:match('^(/.+/)')
if anystring then
return string
else
return false
end
end
local mystring = anystring('/var/log/test.log')
print(mystring)
output: /var/log/
You can be as specific as possible when putting the pattern to avoid code errors

Resources