How to string.find the square bracket character in lua? - string

So I'm trying to find square brackets inside a string:
s = "testing [something] something else"
x,y = string.find(s,"[")
which gives me an error: malformed pattern (missing ']').
I also tried:
x,y = string.find(s,"\[")
giving me the same error.
And this:
x,y = string.find(s,"\\[")
in this case x and y are nil.
Any thoughts on how to do this properly? Thanks in advance.

John's answer will work -- turning off pattern matching.
What you're trying to do -- escape the [ -- is done with the % character in Lua:
x,y = string.find(s,'%[')
Also strings in Lua all have the string module as their metatable, so you could just say:
x,y = s:find('%[')
or even:
x,y = s:find'%['

Use the fourth argument to string.find, which turns off pattern-matching.
x, y = string.find(s, "[", nil, true)

Related

What is wrong with my MathJax square bracket syntax?

This mathjax expression (in an asciidoctor document in a VS Code preview using asciidoctor-vscode) fails to render correctly:
stem:[ = x_l = x_( ([m]+1) /2) ]
The ] after the m acts like a ) for the _, and ends it early. How can I force the parser to understand my brackets please?
If the inline stem equation contains a right square bracket, you must escape this character using a backslash.
Found in Equations and Formulas (STEM), see example 4. What you want to write is:
stem:[ = x_l = x_( ([m\]+1) /2) ]
MathJax is rubbish, rather use latexmath:[ = x_l = x_{\frac{[m\]+1}{2}} ]

Python: How to define string indices as variables

(New to Python after years of R use)
Say I have a string:
dna = "gctacccgtaatacgtttttttttt"
And I want to pre-define the indices of interest:
window_1 = 0:3
window_2 = 1:4
window_3 = 2:5
This is invalid python syntax. So I tried:
window_1 = range(0, 3)
This does not work when I try to use the window_1 variable as a string index:
dna[window_1]
But I get "string indices must be integers" error.
I have tried numerous things such as wrapping range() in int() and / or list() but nothing works.
Thanks
When you're setting your variables window_1, window_2, and window_3, first you have to tell it where you want it to look to grab these indices you're telling it to grab, so you need to tell it to look in your variable 'dna'. Secondly, the indices should be in square brackets. Also keep in mind that Python uses a zero based numbering system. So, the first position in your dna sequence(g) as far as Python is concerned is the zero position. The second position (c) is actually the number 1 position.
dna = "gctacccgtaatacgtttttttttt"
window_1 = dna[0:3]
window_2 = dna[1:4]
window_3 = dna[2:5]

Prolog: Checking if the first and last character of a string are left and right squiggly brackets('{' & '}')

I am very new to prolog, so assume that I know very little terminology.
I am using swipl in SWI-prolog.
I want to check if a string starts with a left squiggly bracket('{') and ends with a right squiggly bracket('}'}
Some answers that I have read online have lead me to program the following into my knowledge base to check if the string starts with a left squiggly bracket.
start_left_squiggle([Letter|_]):-
Letter = '{'.
But when I run this function, I get false, when I expect it to return true.
?- start_left_squiggle('{hello').
false.
As well, answers that seem correct for checking the if the last character is a squiggly bracket have lead me to code the following.
last_char(str, X):-
name(S, N),
reverse(N, [F|_]),
name(X, [F]).
end_right_squiggle(Werd):-
last_char(Werd, Last),
Last = '}'.
And I again get false when running the function, when I expect it to return true.
?- end_right_squiggle('hello}').
false.
Use sub_atom(Atom, Before, Length, After, Subatom) like so:
?- sub_atom('{abc}',0,1,_,C).
C = '{'.
?- sub_atom('{abc}',_,1,0,C).
C = '}'.
Or just test:
?- sub_atom('{abc}',0,1,_,'{').
true.
?- sub_atom('{abc}',_,1,0,'}').
true.
First thing you need to do is to break the atom into list of characters like this:
start_with_left(H):-
atom_chars(H,X), %here x is a list
X = [L|_], %get the head of the list which is frist element an compare
L == '{'.
You can use a recursive definition to check righ side of the atom after converting the atom into list of characters and when length of the list is 1 then compare it with bracket , it means if last element is same you should get true otherwise False.
Right is like this, it's same but we need last element so we have to use recursion:
start_with_right(H):-
atom_chars(H,X), %here x is a list
length(X,Y),
check_at_end(X,Y).
check_at_end([H|_],1):-
H == '}'.
check_at_end([_|T],Y):-
NewY is Y -1,
check_at_end(T,NewY).
.

Error when take two numbers out of a string

I'm just playing around with Lua trying to make a calculator that uses string manipulation. Basically I take two numbers out of a string, then do something to them (+ - * /). I can successfully take a number out of x, but taking a number out of y always returns nil. Can anyone help?
local x = "5 * 75"
function calculate(s)
local x, y =
tonumber(s:sub(1, string.find(s," ")-1)),
tonumber(s:sub(string.find(s," ")+3), string.len(s))
return x * y
end
print(calculate(x))
You have a simple misplaced parenthesis, sending string.len to tonumber instead of sub.
local x, y =
tonumber(s:sub(1, string.find(s," ")-1)),
tonumber(s:sub(string.find(s," ")+3, string.len(s)))
You actually don't need the string.len, as end of string is the default value for sub if nothing is given.
EDIT:
You can actually do what you want to do way shorter by using string.match instead.
local x,y = string.match(s,"(%d+).-(%d+)")
Match looks for tries to match the string with the pattern given and returns the captured values, in this case the numbers. This pattern translates to "One or more digits, then as few as possible of any character, then one or more digits". %d is 1 digit, + means one or more. . means any character and - means as few as possible. The values within the parentheses are captured, which means that they are returned.

String concatenation with spaces

I would like to concatenate strings. I tried using strcat:
x = 5;
m = strcat('is', num2str(x))
but this function removes trailing white-space characters from each string. Is there another MATLAB function to perform string concatenation which maintains trailing white-space?
You can use horzcat instead of strcat:
>> strcat('one ','two')
ans =
onetwo
>> horzcat('one ','two')
ans =
one two
Alternatively, if you're going to be substituting numbers into strings, it might be better to use sprintf:
>> x = 5;
>> sprintf('is %d',x)
ans =
is 5
How about
strcat({' is '},{num2str(5)})
that gives
' is 5'
Have a look at the final example on the strcat documentation: try using horizontal array concatination instead of strcat:
m = ['is ', num2str(x)]
Also, have a look at sprintf for more information on string formatting (leading/trailing spaces etc.).
How about using strjoin ?
x = 5;
m ={'is', num2str(x)};
strjoin(m, ' ')
What spaces does this not take into account ? Only the spaces you haven't mentioned ! Did you mean:
m = strcat( ' is ',num2str(x) )
perhaps ?
Matlab isn't going to guess (a) that you want spaces or (b) where to put the spaces it guesses you want.

Resources