I have the following regular expression:
>> str = 'aaabbbaaa';
>> regexp(str, '^a+')
ans = 1
How do I use a variable in the pattern for the regular expression? Something like the following:
>> str = 'aaabbbaaa';
>> searchchar = 'a'
>> regexp(str, '^searchchar')
You need to insert the value of the variable into a string. One way is concatenating characters:
str = 'aaabbbaaa';
searchchar = 'a'
expr = ['^',searchchar,'+'];
regexp(str, expr)
A different way is to use sprintf to build the expression string:
expr = sprintf('^%s+',searchchar);
I solved this with a string concatenation:
>> str = 'aaabbbaaa'
>> searchchar = 'a'
>> regexp(str, cstrcat('^', searchchar, '+'))
ans = 1
Related
I am not sure what is the right way to do this.
I basically want to return all values if value for certain filter is not defined.
Get request is made with filters like this:
url.com?filter1=abc&filter2=123&filter4=33
so as filter3was not defined i want to return all values regardless what their filter3 value is. Easy logic right.
But if I try to implement in SQL, I get stuck.
SELECT * from TABLE_NAME
WHERE filter1 = $1
AND filter2 = $2
AND filter3 = $3
AND filter4 = $4
.
How can I modify SQL above to respond to undefined/blank value and return all. Or is this even correct strategy.
If you have indexes, it is better to build the custom SQL. But, if performance is less of an issue (say the table is small), just do the explicit comparison:
SELECT *
FROM TABLE_NAME
WHERE ($1 IS NULL or filter1 = $1) AND
($2 IS NULL or filter2 = $2) AND
($3 IS NULL or filter3 = $3) AND
($4 IS NULL or filter4 = $4);
If the value is passed in as something other than NULL, then adjust the logic accordingly. For instance:
WHERE ($1 = '' or filter1 = $1) AND
($2 = '' or filter2 = $2) AND
($3 = '' or filter3 = $3) AND
($4 = '' or filter4 = $4);
I receive a CSV file daily in which I filter to look for certain data. This file requires a lot of manual effort within Excel to filter and format the data. I am devising a VBScript to look at each line to return only the data needed to reduce the manual effort.
Within the CSV file is a "time seen" string which is formatted strangely. The "time seen" data differs from line to line. An example of this data is the following:
3hrs27min 35sec
35min 20sec
8min 38sec
1days1hrs25min 30sec
5days12hrs9min 48sec
I am using this code snippet to remove the "days", "hrs", "min ", and "sec" from the data and replace them with a ":".
strLastField0 = arrFields(9)
strLastField1 = Replace(strLastField0,"min ",":")
strLastField2 = Replace(strLastField1,"hrs",":")
strLastField3 = Replace(strLastField2,"days",":")
strLastField4 = Replace(strLastField3,"sec","")
The result is the following:
d:h:m:s
3:27:35
35:20
8:38
1:1:25:30
5:12:9:48
I am looking to have the data come out formatted in the following manner instead of what it currently is.
hh:mm:ss
03:27:35
00:35:20
00:08:38
25:01:25
132:09:48
Here is a function in which I have been working with to accomplish this, but my attempts have failed to get the formatting like I want.
Function funcFormatTime(TimeString)
Dim TimeArray
Dim h, m, s, hh, mm, ss
TimeArray = Split(TimeString, ":", -1, 1)
d = TimeArray(0)
h = TimeArray(1)
m = TimeArray(2)
s = TimeArray(3)
Do Until s < 60
s = s - 60
m = m + 1
Loop
Do Until m < 60
m = m - 60
h = h + 1
Loop
Do Until h < 24
h = h - 24
Loop
If Len(Trim(h)) = 1 Then hh = "0" & h Else hh = h
If Len(Trim(m)) = 1 Then mm = "0" & m Else mm = m
If Len(Trim(s)) = 1 Then ss = "0" & s Else ss = s
funcFormatTime = hh & ":" & mm & ":" & ss
End Function
This uses a regular expression to split the input strings using the .Replace method with a function pointer that will receive as arguments each of the elements in the string if present or an Empty value if not present.
Option Explicit
Dim aStrings
aStrings = Array( _
"3hrs27min 35sec", _
"35min 20sec", _
"8min 38sec", _
"1days1hrs25min 30sec", _
"5days12hrs9min 48sec" _
)
Dim sTime
For Each sTime in aStrings
WScript.Echo funcFormatTime( sTime )
Next
Function funcFormatTime( inputString )
With New RegExp
.Pattern = "^(?:([0-9]+)days)?(?:([0-9]+)hrs)?(?:([0-9]+)min)?(?:\s*([0-9]+)sec)"
funcFormatTime = .Replace( inputString, GetRef("funcCalcTime") )
End With
End Function
Function funcCalcTime( matchedString, d, h, m, s, offset, originalString )
funcCalcTime = LeftZeroPad( CLng("0" & d) * 24 + Clng("0" & h), 2) & ":" & _
LeftZeroPad( CLng("0" & m), 2) & ":" & _
LeftZeroPad( CLng("0" & s), 2)
End Function
Function LeftZeroPad( value, length )
LeftZeroPad = CStr(value)
If Len(LeftZeroPad) < length Then
LeftZeroPad = Right(String(length, "0") & CStr(LeftZeroPad), length)
End If
End Function
Each of the elements in the regular expression have the form
(?:([0-9]+)days)?
Where (?: )? means that the parenthesis do not define a capture group (?:) and that this group could or couldn't be present (the closing ?). Inside this expression there is a ([0-9]+) that define a capture group that match a sequence of numeric digits. Capture groups are passed as arguments to the replace function, where the only work to do is properly format the values.
I have a list of strings that change dynamically. I need to create a MySQL table where each string in the list is a name of a column.Note: I have found some examples using sqlalchemy but it didn't help me at all.
here is my try:
f = open(filepath,"r")
pluginoutput= f.read()
pluginoptojson = json.loads(pluginoutput)
columnsnames = (pluginoptojson["columns"])
countcolumns = len(pluginoptojson["columns"])
count = 0
lst = []
for name in columnsnames:
if count < countcolumns:
lst.append(str(name))
count +=1
lst.append("caseid")
createsqltable = """CREATE TABLE IF NOT EXISTS %s""" + for t in columnsnames: """ """ (test)
c.execute(createsqltable)
conn.commit()
c.close()
conn.close()
my head is about to explode of thinking. any help will be appreciated.
first thanks alot to Irnzcig.
I just tested his recommendation and it worked like charm. the code is:
pluginoutput= f.read()
pluginoptojson = json.loads(pluginoutput)
columnsnames = (pluginoptojson["columns"])
countcolumns = len(pluginoptojson["columns"])
count = 0
lst = []
for name in columnsnames:
if count < countcolumns:
lst.append(str(name))
count +=1
lst.append("caseid")
table_name = "test1"
createsqltable = """CREATE TABLE IF NOT EXISTS """ + table_name + " (" + " VARCHAR(50),".join(lst) + " VARCHAR(50))"
c.execute(createsqltable)
conn.commit()
c.close()
conn.close()
gc.collect()
two questions:
So I have a list of filenames, each of which I would like to feed into a MYSQL query.
The first questions is how to loop through the filelist and pass the elements (the filenames) as a variable to MYSQL?
The second question is: How do I print the results in a more elegant way without the parenthesis and L's form the Tuple output that is returned? THe way I have below works for three columns, but I'd like a flexible way that I don't have to add sublists (cleaned1, 2..) when I fetch more rows.
Any help highly appreciated!!!
MyConnection = MySQLdb.connect( host = "localhost", user = "root", \
passwd = "xxxx", db = "xxxx")
MyCursor = MyConnection.cursor()
**MyList= (File1, File2, File3, File...., File36)
For i in Mylist:
do MYSQL query**
SQL = """SELECT a.column1, a.column2, b.column2 FROM **i in MyList** a, table2 b WHERE
a.column1=b.column1;"""
SQLLen = MyCursor.execute(SQL) # returns the number of records retrieved
AllOut = MyCursor.fetchall()
**List = list(AllOut) # this puts all the TUple information into a list
cleaned = [i[0] for i in List] # this cleans up the Tuple characters)
cleaned1 = [i[1] for i in List] # this cleans up the Tuple characters)
cleaned2 = [i[2] for i in List] # this cleans up the Tuple characters)
NewList=zip(cleaned,cleaned1,cleaned2) # This makes a new List
print NewList[0:10]**
# Close the files
MyCursor.close()
MyConnection.close()
I can figure out the saving to file, but I don't know how to pass a python variable into MYSQL.
convert the tuple to a list first: using
MyList = list(MyList)
and you will have two options:
try this:
for tablename in MyList:
c.execute("SELECT a.column1, a.column2, b.column2 FROM %s a, table2 b WHERE a.column1=b.column1", (tablename))
or :
for tablename in MyList:
SQL= "SELECT a.column1, a.column2, b.column2 FROM tablevar a, table2 b WHERE a.column1=b.column1"
SQL = SQL.replace('tablevar', tablename)
c.execute(SQL)
to print the results without the brackets you can use :
for tablename in MyList:
print tablename
I need to find a way to dump key/value pairs of PL/pgSQL function input parameters:
CREATE OR REPLACE FUNCTION _test(A text, B text)
...
raise info 'Params dump: %', _x;
...
when executed:
select _text('HELLO', 'WORLD');
the function raises info as follows:
'A = HELLO, B = WORLD'
Is there a way to dump input parameter key/value pairs into a variable?
It's possible if you can make the function VARIADIC with uniform argument types, and can print the array. You don't get argument names, since they don't have names, but you do get argument positions.
Otherwise no, it is not possible in PL/PgSQL, though it should be in other PLs like PL/Perl, PL/Python, etc.
It'd be quite nice to be able to get a RECORD with all the function arguments in it, so you could print it, feed it to the hstore extension, etc, but this isn't currently possible.
There is an awkward way of dumping input parameters :
create or replace function _tester(
_txt text,
_int int
) returns void
language 'plpgsql' as
$$
declare
_out text = '';
_rec record;
_func_name text = '_tester';
begin
for _rec in SELECT parameters.ordinal_position as _pos, parameters.parameter_name as _nm
FROM information_schema.routines
JOIN information_schema.parameters
ON routines.specific_name=parameters.specific_name
WHERE routines.routine_name = _func_name
ORDER BY parameters.ordinal_position
loop
if _rec._pos = 1 then
_out = _out || _rec._nm || ' = ' || $1::text || chr(10);
elsif _rec._pos = 2 then
_out = _out || _rec._nm || ' = ' || $2::text || chr(10);
end if;
end loop;
raise notice '%', _out;
end;
$$;
select _tester('A','1');
NOTICE: _txt = A
_int = 1
Notice that must add as many if/elsif as there are input parameters. Not sure if that part can be more concise.