lua sub string replace 2 pattern - lua

due to using nginx lua (kong gateway)
would like to replace
from
{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"samplePassword\",\r\n"}
to
{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"***REDACTED***\",\r\n"}
from
username=sampleUser&password=samplePassword
to
username=sampleUser&password=***REDACTED***
from
"password" : "krghfkghkfghf"
to
"password" : "***REDACTED***"
i did try on sample https://stackoverflow.com/a/16638937/712063
local function replacePass(configstr, newpass)
return configstr:gsub("(%[\"password\"%]%s*=%s*)%b\"\"", "%1\"" .. newpass .. "\"")
end
it does not work, any recommended reference ?

maybe something like this:
local t = {
[[{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"samplePassword\",\r\n"} ]],
[[username=sampleUser&password=samplePassword]],
[["password" : "krghfkghkfghf"]]
}
local newpass ="***REDACTED***"
for k,example in pairs(t) do
res = example:gsub('(password[\\" :]+)(.-)([\\"]+)',"%1"..newpass.."%3")
res = res:gsub("(password=).+","%1"..newpass)
print(res)
end
out:
{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"***REDACTED***\",\r\n"}
username=sampleUser&password=***REDACTED***
"password" : "***REDACTED***"

There's several things wrong with that at first sight.
1. You only check for =
In your test data you seem to have cases with key = value as well as key : value but your pattern only checks for =; replace that with [=:] for a simple fix.
2. You can't balance quotation marks
I don't know how you expect this to work, but [[%b""]] just finds the shortest possible string between two " characters, just as [[".-"]] would. If that's your intention, then there's nothing wrong with writing it using %b though.
3. Just don't
As I don't know the context, I can't say if this really is a bad idea or not, but it does seem like a very brittle solution. If this is an option, I would recommend considering the alternative and going with something more robust.
As for what a better alternative could look like, I can't say without knowledge of your requirements. Maybe normalizing the data into a Lua table and replacing the password key in a uniform way? This would make sure that the data is either sanitized, or errors during parsing.
Beyond that, it would help if you told us how it doesn't work. It's easy to miss bugs when reading someone elses code, but knowing how the code misbehaves can help a lot with actually spotting the problem.
EDIT:
4. You didn't even remove the brackets
You didn't even remove the [] from that other stack overflow answer. Obviously that doesn't work without any modifications.

Related

ruby substring backslash plus "

So, I have a string like this:
str1 = "blablablabla... original_url=\"https://facebook.com/125642\"> ... blablablabla..."
what is the best approach to extract this original_url?
what I have done so far is this:
original_url = str1['content'][str1['content'].index('original_url')+12..str1['content'].index('>')-2]
it works, but it seems such like a poor solution, mostly I'm stuggling to find this substring /">
here's what I have tried so far
str1.index('\">')
str1.index('\\">') # escaping only one backslach
str1.index('\\\">') # escaping both back slash and "
str1.index("\\\">") # was just without idea over here
I'm not a ruby programmer, so I'm kinda lost here
The best approach to parse xml namespaces is to use Nokogiri as suggested by #spickermann.
Quick but not elegant and not even efficient solutions:
str1 = "blablablabla... original_url=\"https://facebook.com/125642\"> ... blablablabla..."
original_url=str1[str1.index("original_url")+14...str1.index("\">")]
# => "https://facebook.com/125642"
original_url=str1.split(/original_url=\"/)[1].split(/">/).first
# => "https://facebook.com/125642"

Adding labels to my programming language

Actually I am writting a programming language in Lua. It was quite fun. I've wrote a bit of standard library (stack op and simple io). Then I've thought about labels. It would look like in assembly. While and for loop aren't funny in any bit so programming in that language can be quite challenging. Here are some requirements for this system:
Label stack (or array, dictionary) must be accessible from global context.
Jump instruction handler will be in separate file.
This is how my label-handling function look like:
function handleLabel(name,currentLine)
end
I have no idea how to implement this kind of magic. First I've thought about that:
LabelLineIDS = {}
Labels = {}
Labelamount = 1;
function handleLabel(name,currentLine)
LabelLineIDS[Labelamount]=currentline
Labels[Labelamount]=name
Labelamount=Labelamount+1
end
-- In file "jump.lua":
local function has_value (tab, val)
for index, value in ipairs(tab) do
if value == val then
return index
end
end
print ("Error: Label not defined.") -- Bail out.
os.exit(1)
end
local function _onlabel()
local labelName = globalparams --Globalparams variable contain parameters to each function, at the moment
--this will contain label name. It _can_ be nil.
return LabelLineIDS[has_value(Labels, labelName)]
end
CurrLine = _onlabel() --Currline - current line that get's parsed.
--1 command per one line.
But I'm unsure is this well written or even work. Can you give me idea how to parse labels in my programming language (and write jump functions)? Or if my code is pretty ok at the moment, can you help me to improve it?
Using line counter in my parser I've decided to implement gotos like we can see in BASIC. Thanks everyone for help.

WoW API / Lua - Math.Random(#,#)

Always feel like I'm making something far more complicated than it has to be. I'm currently playing around with the WoW addon, Tongues, in hope of make a custom dialect filter - which is quite easy of course, very noob-friendly. At this point, there is one thing I want to accomplish-- something of which feels to have the implications far beyond this -- that is just novelty, but before I give up completely (lots of hours trying different things with no headway) I was hoping someone could come by, get a cheap laugh and perhaps help me fix this if they understand my point. And who knows, posting this new helpless questions might bump me up to being able to finally upvote!
Tongues.Affect["Drunk"] = {
["substitute"] = {
[1] = merge({
{ ["([%a]+)(%A*)$"] = "%1 ...hic!"},
Tongues.Affect["Slur"]["substitute"][1]
});
};
["frequency"] = 100;
};
What this does is simply add on the "...hic!" to sendchatmessage(); I believe it is. The frequency part seems completely broken and only the GUI slider in the game matters for that. What I was hoping to accomplish was to repurpose this and make the "...hic!" an actual randomized word. Since the mod itself handles the chance that it happens, I figured all that is needed left is to replace the string with a function=X. It's, of course, intensely way over my head, but despite checking the Lua of several mods, nothing feels like "it will fit."
The best I could come up with,
Tongues.Affect["TESTAFFECT"] = {
["substitute"] = {
[1] = merge({
{ ["([%a]+)(%A*)$"] = function(b)
local rand = Math.Random(1,2)
if (rand == 1) then
b = "test1"
return b
elseif (rand == 2) then
b = "test2"
return b
end
end
Leaves a gloriously useless message in the error mod BugSack - of course my attempt is wrong, but there's no way to know how!
I'm assuming this is enough information - as I said, very user friendly mod without any need to understand how it really works (Although I'd love to ready study it after this "project")
Anyone? Regardless, thank you for your time in simply even reading this far.
Update: Downvotes, okay! That's cool too. A little unpredictable, but sure. The error is as follows
15x Tongues\Core\dialects.lua:172: attempt to index field 'Affect' (a nil value)
Tongues\Core\dialects.lua:172: in main chunk
Locals:
175 in dialects.lua is
Tongues.Affect["Wordcut"]["substitute"][1],
Which has nothing to do with what I'm trying to accomplish, and works just fine.
Sorry that my question was an inconvenience. I asked to the best of my ability and the best of my ability to articulate the question proved to be less then stellar. The example codes I had provided were the only way I could articulate showing what I was trying to do.
I was misinterpreting the error frame and discovered that behind the useless stack that calls an error where there is, in fact, none, is a stack that calls the error in syntax at the time that broke it.
I'm sharing my results, regardless if the community finds this useless. I learned a tremendous amount from this personally, which is the only incentive in that I asked for help.
Tongues.Affect["TEST"] = {
["substitute"] = {
[1] = {
["([%a]+)"] = function(a)
return a
end;
["(%A*)$"] = function(a,b)
local rand = math.random(1,2)
if (rand == 1) then
b = "test1"
return b
end;
if (rand == 2) then
b = "test2"
return b
end;
end;
};
};
};
Hope it helps someone out there - as expected, I made it more complicated than it had to be. Simply "jiggling" the symbols is all that was needed.

NSString to NSDictionary

I have a string (from HTTP Header) and want to split it into a dictionary.
foo = \"bar\",baz=\"fooz\", beta= \"gamma\"
I ca not guarantee that the string is the same every time. Maybe there are spaces, maybe not, sometimes the double quotes are escaped, sometimes not.
So I found the solution in PHP with regular expressions. Unfortunately I can't convert it to work on iOS.
preg_match_all('#('.$key.')=(?:([\'"])([^\2]+?)\2|([^\s,]+))#', $input, $hits, PREG_SET_ORDER);
foreach ($hits as $hit) {
$data[hit[1]] = $hit[3] ? $hit[3] : $hit[4];
}
Can anybody help me converting this to Objective-C?
I met a guy which is kinda RegEx guru. He explained the whole stuff and I got the following (working!!!!) solution in RegEx.
This gives me strings like foo="bar":
(?<=[,\\s])((realm|qop|nonce|opaque)=(?:([\"'])([^\2]+?)\2|([^\\s,]+)))
I then use another RegEx to split it by key and value to create a dictionary.

Lua arguments passed to function in table are nil

I'm trying to get a handle on how OOP is done in Lua, and I thought I had a simple way to do it but it isn't working and I'm just not seeing the reason. Here's what I'm trying:
Person = { };
function Person:newPerson(inName)
print(inName);
p = { };
p.myName = inName;
function p:sayHello()
print ("Hello, my name is " .. self.myName);
end
return p;
end
Frank = Person.newPerson("Frank");
Frank:sayHello();
FYI, I'm working with the Corona SDK, although I am assuming that doesn't make a difference (except that's where print() comes from I believe). In any case, the part that's killing me is that inName is nil as reported by print(inName)... therefore, myName is obviously set to nil so calls to sayHello() fail (although they work fine if I hardcode a value for myName, which leads me to think the basic structure I'm trying is sound, but I've got to be missing something simple). It looks, as far as I can tell, like the value of inName is not being set when newPerson() is called, but I can't for the life of me figure out why; I don't see why it's not just like any other function call.
Any help would be appreciated. Thanks!
Remember that this:
function Person:newPerson(inName)
Is equivalent to this:
function Person.newPerson(self, inName)
Therefore, when you do this:
Person.newPerson("Frank");
You are passing one parameter to a function that expects two. You probably don't want newPerson to be created with :.
Try
Frank = Person:newPerson("Frank");

Resources