well i am currently writing a script that is meant to check the logs of another script i wrote to see if it has had three or more unsuccessful pings in a row before a successful one, this is just barebones at the moment but it should look something like this
fileread,x,C:\Users\Michael\Desktop\ping.txt
result:=RegExMatch(%x% ,failure success)
msgbox,,, The file is = %x% `n the result is = %result%
now the file that is trying to read is
success failure success
and for some reason, when it reads the file it says that the variable %x% 'contains illegal characters
when i copy and paste the contents of ping.txt into the script and save it as a variable it works
i have made sure that the file has windows line endings CR +LF
i have assigned the variable generated in file read as another variable thus stripping any trailing or leading whitespace characters
the file is encoded in ANSI and still has the problem with UTF8
Function parameters take variable names without the % symbol, simply remove them.
I also want to point out that if the second parameter is meant to be a regular expression,
instead of a variable containing a regular expression, you will need quotes around it.
As is your script passes an empty string as the pattern which will always return 1
(failure is interpreted as a variable with an empty string associated with it.).
To quote Lexikos:
"An empty string, when compiled as a regex pattern, will match exactly
zero characters at whatever position you attempt to match it. Think of
it this way: For any position n in any string, the next 0 characters
are always the same."
Because you are simply truth testing,
or finding the index I want to point out that Autohotkey has a useful shorthand operator for this.
string := "this is a test"
f1::
result := RegExMatch(string, "\sis")
traytip,, %result%
Return
f2::
result := string ~= "\sis"
traytip,, % result
Return
These hotkeys both do the same thing; the second uses the shorthand operator ~=
and notice how the traytip parameter in the second example has only one %
When you start a command parameter with a % that starts an expression,
and within an expression variables are not enclosed with %.
The ternary operator ?: is also very useful:
string := "this is a test"
f3::traytip,, % (result := string ~= "\sis") ? (result) : ("nothing")
It might look complicated but it's very simple.
Think of
% as if
? as then
: as else
If (true) then (a) else (b)
% (true) ? (a) : (b)
A variable will be evaluated as False if 0 (or nothing) is assigned to it.
But in this example "\sis" is matched and the index of the space is returned (5),
so it is evaluated as True.
You can read more about variables and operators here:
http://l.autohotkey.net/docs/Variables.htm
Related
I have the text file contains the below text which I need to filter based on condition.
CODE=0xea00e60c
CODE=0xea00e60d
OUTPUT="HW Address: 91183010\n,HWType:00000030\n"
CODE=0xea00e60e
CODE=0xea01ff00
If the line starts with CODE, extract everything after 0x(e.g ea00e60c) from 1st line and paste in xyz file.
If the line starts with OUTPUT, extract out everything under double quotes and paste in xyz files. Sequence of extracting and putting the text in XYZ file should be maintained.
def filter_logs(filename)
postcode = "postcode_logs"
File.open(filename, 'r').each do |line|
result = (line.scan(/"(.*?)"/)) || (line.split("x")[1])
File.open(postcode, 'a') do |selected_line|
selected_line.puts(result)
end
end
end
filename and postcode is file defined already.
There is no error in code but output is also not there.
**Expected output**
ea00e60c
ea00e60d
HW Address: 91183010\n,HWType:00000030\n
ea00e60e
ea01ff00
**current output**
HW Address: 91183010\n,HWType:00000030\n
The reason this doesn't succeed is because #scan always succeeds. If nothing is found an empty array is returned (which evaluates as truthy). Simply getting the first result should be good enough (returning nil for empty arrays):
result = line.scan(/"(.*?)"/).first || line.split("x")[1]
Although you could also use other techniques like:
result = line[/\ACODE=0x(\h*)/, 1]
result ||= line[/\AOUTPUT="([^"]*)"/, 1]
Matching from the start of the string either CODE=0x followed by zero or more hexadecimal characters (\h*) capturing them in group 1 or OUTPUT=" followed by zero or more non-quote characters ([^"]*) capturing them in group 1 followed by a ".
Check out the regular expression documentation for Ruby if anything is unclear about the regex. Check out the documentation of the square bracket accessor of String if anything is unclear about the square bracket method usage.
Can anyone help me on this script?
What did the function do?
Thanks!
========================================================
&AAA=0
if (string.scan(string.lwr("¶meters"),"AAA",0)!=-1)
(
&AAA=1
)
========================================================
Well I guess your code looks like this:
&AAA=0
if (string.scan(string.lwr("¶meters"),"AAA",0)!=-1)
(
&AAA=1
)
Note: The round brackets for opening and closing a block in a PRACTICE script must be placed in separate lines.
About the meaning: Your script has two "variables" (aka. "macro"): ¶meters and &AAA.
In the first line you initialize &AAA with 0.
In the second line you use string.lwr() to get the content of the variable ¶meters converted to lower-case.
Then you search in this lower-case string for a string "AAA" (which is ironically upper case) beginning from the first letter (with string.scan()).
The result of string.scan() is -1 if the string "AAA" wasn't part of the lower-case version of ¶meters
So variable &AAA gets set to 1, if a lower-case version of ¶meters contain the string "AAA" (which is never the case since "AAA" is upper-case).
Maybe the writer of the script wanted to use string.upr() instead of string.lwr().
I am pretty new to Perl. I have the following code fragment that works just fine, but I don't fully understand it:
for ($i = 1; $i <= $pop->Count(); $i++) {
foreach ( $pop->Head( $i ) ) {
/^(From|Subject):\s+/i and print $_, "\n";
}
}
$pop->Head is a string or an array of strings returned by the function Mail::POP3Client, and it is the headers of a bunch of emails. Line 3 is some kind of regular expression that extracts the FROM and the SUBJECT from the header.
My question is how does the print function only print the From and the Subject without all the other stuff in the header? What does "and" mean - this surely can't be a boolean and can it? Most important, I want to put the From string into its own variable (my $fromline). How do I do this?
I am hoping that this will be easy for some Perl professional, it has got me baffled!
Thanks in advance.
ARGHHH... The question was edited while I was typing the answer. OK, throwing out the part of my answer that's no longer relevant, and focusing on the specific questions:
The outer loop iterates over all the messages in the mailbox.
The inner loop doesn't specify a loop variable, so the special variable $_ is used.
In each iteration through the inner loop, $_ is one header line from message number $i.
/^(From|Subject):\s+/i and print $_, "\n";
The first part of this line, up to the and is a pattern. We didn't specify what to do with the pattern, so it's implicitly matched against $_. (That's one of the things that makes $_ special.) This gives us a yes/no test: does the pattern match the header line or not?
The pattern tests whether that item begins with (<) either of the words "From" or "Subject", followed immediately by a colon and one or more whitespace characters. (This not the correct pattern to match an RFC 822 header. Whitespace is optional on both sides of the colon. The pattern should more properly be /^(From|Subject)\s*:\s*/i. But that's a separate issue.) the i at the end of the pattern says to ignore case, so from or SUBJECT would be OK.
The and says to continue evaluating (i.e., executing) the expression if there is a match. If there's no match, whatever follows and is ignored.
The rest of the expression prints the header line ($_) and a newline ("\n").
In perl, and and or are boolean operators. They're synonyms for && and ||, except that they have much lower precedence, making it easier to write short-ciruit expressions without clutter from lots of parentheses.
The smallest change that captures the From line into a separate variable would be to add the following line to the inner loop:
/^From\s*:\s*(.*)$/i and $fromline = $1;
You should probably also put
$fromline = undef
before the loop so you can test, after the loop, whether there was a From: line.
There are other ways to do it. In fact, that's one of the mantras of perl: "There's more than one way to do it." I've stripped out the "From: " from the beginning of the line before storing the balance in $fromline, but I don't know your needs.
It's a logical and with short-circuiting. If the left side evaluates to true -- say, if that regular expression matches -- it'll evaluate the right side, the print.
If the expression on the left is false, it doesn't need to evaluate the right hand side, because the net result would still be false, so it skips it.
See also: perldoc perlop
please help me decipher the regular expression-
'!_[$0]++'
It is being used to get a MSISDN (one at a time from a file containing list of MSISDN starting with zero )by the following usage:
awk '!_[$0]++' file.txt
It's not a regular expression, it's an arithmetic and boolean expression.
$0 = The current input line
_[$0] = An associative array element whose key is the input line
_[$0]++ = increment that array element each time we encounter a repeat of the line, but evaluates to the original value
!_[$0]++ = boolean inverse, so it returns true if the value was originally 0 or the empty string, false otherwise
So this expression is true the first time a line is encountered, false every other time. Since there's no action block after the expression, the default is to print the line if the expression is true, skip it when false.
So this prints the input file with duplicates omitted.
'true'- then the line will be printed
'_[$0]++'- associative array will be incremented everytime when $0 is present.means it will set the number of times each line is repeated.
'!_[$0]++'-this will be true when a line is inserted in the associative array for the firsttime only and the rest of the times it will resolve to false ultimately not printing the line.
So all the duplicate lines will not be prited.
This is not a regular expression. This particular command prints unique lines the first time they are found.
_ is being used as an array here and $0 refers to the entire line. Given that the default numeric value for array element is 0 (it's technically an empty string, but in numeric contexts its treated as 0), the first time you see a line, you print the line (since _[$0] is falsy, !_[$0] will be true). The command increments every time it sees a line (after printing -- awk's default command is to print), so the next time you see the line _[$0] will be 1 and the line will not be printed
I have a piece of lua code (executing in Corona):
local loginstr = "emailAddress={email} password={password}"
print(loginstr:gsub( "{email}", "tester#test.com" ))
This code generates the error:
invalid capture index
While I now know it is because of the curly braces not being specified appropriately in the gsub pattern, I don't know how to fix it.
How should I form the gsub pattern so that I can replace the placeholder string with the email address value?
I've looked around on all the lua-oriented sites I can find but most of the documentation seems to revolve around unassociated situations.
As I've suggested in the comments above, when the e-mail is encoded as a URL parameter, the %40 used to encode the '#' character will be used as a capture index. Since the search pattern doesn't have any captures (let alone 40 of them), this will cause a problem.
There are two possible solutions: you can either decode the encoded string, or encode your replacement string to escape the '%' character in it. Depending on what you are going to do with the end result, you may need to do both.
the following routine (I picked up from here - not tested) can decode an encoded string:
function url_decode(str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)",
function(h) return string.char(tonumber(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end
For escaping the % character in string str, you can use:
str:gsub("%%", "%%%%")
The '%' character is escaped as '%%', and it needs to be ascaped on both the search pattern and the replace pattern (hence the amount of % characters in the replace).
Are you sure your problem isn't that you're trying to gsub on loginurl rather than loginstr?
Your code gives me this error (see http://ideone.com/wwiZk):
lua: prog.lua:2: attempt to index global 'loginurl' (a nil value)
and that sounds similar to what you're seeing. Just fixing it to use the right variable:
print(loginstr:gsub( "{email}", "tester#test.com" ))
says (see http://ideone.com/mMj0N):
emailAddress=tester#test.com password={password}
as desired.
I had this in value part so You need to escape value with: value:gsub("%%", "%%%%").
Example of replacing "some value" in json:
local resultJSON = json:gsub(, "\"SOME_VALUE\"", value:gsub("%%", "%%%%"))