I have problem using REGEX in Mysql
I have oid value in database like this
id -> value
1.3.6.1.4.1 -> Value a
1.3.6.1.4.1.2499.1.1.2.1.1.1.1.1 -> Value b
1.3.6.1.4.1.2499 -> Value c
And my objecttives are
1. To get single oid & value with the specific oid that i put into sql statement
2. If no specific value then it should reverse the oid number by number until it found the newrest value
For example
If i use
[select id from tablename where '1.3.6.1.4.1.2499.1.1.2.1.1.1.1.1' REGEXP oid]
it should return only 1.3.6.1.4.1.2499.1.1.2.1.1.1.1.1 but the above sql will return all result
If i use
[select id from tablename where '1.3.6.1.4.1.24999999.5' REGEXP oid]
it should return 1.3.6.1.4.1 only but it return 1.3.6.1.4.1 and 1.3.6.1.4.1.2499
If i use
select id from tablename where '1.3.6.1.4.1.2499.1.1.2.1.1.1.1.100' REGEXP oid
it should return 1.3.6.1.4.1.2499 only but it return all ids
I am not really familiar with this REGEXP. Can anyone help me to solve this problem.
Thank you
With MySQL, you should use field REGEXP value, like this:
select id from tablename where oid REGEXP '1.3.6.1.4.1.2499.1.1.2.1.1.1.1.1'
. must be escaped with \
And to match an entire row, use ^ and $:
select id from tablename where oid REGEXP '^1\.3\.6\.1\.4\.1\.2499\.1\.1\.2\.1\.1\.1\.1\.1$'
I don't understand why do you use REGEXP when you can select by LIKE, because you don't search by a regular expression.
I don't think regex is the right tool for this job.
Instead, I'd loop over the input string, treating it as a period-delimited list.
Match the list against oid. If zero matches, remove the last list element. Repeat.
Related
I want to pass an array like [group1, group2, group3] and then filter the Postgres table column groups.
Create or replace function funname(groups text[])
Select *
From tableName
Where groupscolumn #> groups
Also kindly write the function for the same, getting an error while defining character varying [].
It's unclear to me what you want, but maybe you are looking for the ANY operator?
select *
from some_unknown_table
where group_column = any(array_parameter);
This requires that the data type of the group_column and the one of the parameter match. E.g. if group_column is text or varchar the parameter needs to be declare as text[]. If group_column is e.g. an integer, the parameter needs to be declared as integer[]
You can use the unnest function to convert an array in 'table' output and then filter the value that you need, for example:
SELECT * FROM (
SELECT unnest (ARRAY['group1','group2','group3']) AS arr
) AS sub WHERE arr ='group3'
You can use join for groups array and SELECT WHERE group IN groups for filter:
import psycopg2
def filter_groups(group_names):
try:
# connect to BD
connection = psycopg2.connect(
host="host",
user="user",
password="pass",
database="db_name"
)
except Exception as _ex:
print("[INFO] Connection error", _ex)
try:
with connection.cursor() as cursor:
placeholders = ','.join(['%s'] * len(group_names))
rsql = f"SELECT * FROM table_name WHERE groups IN ({placeholders})"
cursor.execute(rsql, group_names)
rows = cursor.fetchall()
cursor.close()
except Exception as _ex:
print("[INFO] Error while working with PostgreSQL", _ex)
if connection:
connection.close()
print("[INFO] PostgreSQL connection closed.")
return rows
I have to search certain nodes like eq.page whether or not they have relation or not with some other node..like tags.
If they are connected to tag nodes then search for the search string in page name and the tag names
Else search for the search string in page name only
MATCH ...//nodes of certain type
WHERE
if r is null'
...//Match query without relation for searching
else
...//Match query without relation for searching
Return ...
MATCH (n:page)<-[r:pagetag]-(tag)
if r is null
then n.title CONTAINS 'java'or tag.name IN ["java"]
return distinct n.name
else n.title CONTAINS 'java'return distinct n.name
END
This query is giving error. May be syntax problem. But I want to search for like this only for the pages.
Finally acheieved what I wanted. Thanks all. OPTIONAL Match worked great for me.
MATCH (s:page)
WITH s
OPTIONAL MATCH (s)<-[r:pagetag]-(tag)
WITH s,r,tag
Where s.pagename contains 'juniors'or tag.name contains 'math'
return distinct s.pagename
Isn't that just basic conditionals?
MATCH (n:page)<-[r:pagetag]-(tag)
WITH n,r,tag
WHERE r IS NULL AND (n.title CONTAINS 'java' or tag.name IN ["java"])
OR NOT r is NULL AND (n.title CONTAINS 'java')
return distinct n.name
I don't think you can use if else in Neo4j you have to use case, or foreach to simulate if .
I am using Mockrunner to mock Sql DB for my unit tests. Following is my query:-
"select * from table where userId in (" + userIds + ")"
Now my userIds is state dependent. I don't need my test cases dependent on the arrangement inside the list - userIds. So I don't need exact match but regex matching. I have already enabled regex matching by below code:-
StatementResultSetHandler statementHandler = connection.getStatementResultSetHandler();
usersResult = statementHandler.createResultSet("users");
statementHandler.setUseRegularExpressions(true);
//How to write this regex query?
statementHandler.prepareResultSet("select * from table where userId in .*", campaignsResult);
But as it is noted, I have no idea about the regex syntax supported by Mockrunner.
Edit: I unable to match queries like "Select * from tables" with "Select * from tab .*". So It has to do something with the way I using regex with Mockrunner
There are some helpful examples available here. For instance:
public void testCorrectSQL() throws Exception {
MockResultSet result = getStatementResultSetHandler().createResultSet();
getStatementResultSetHandler().prepareResultSet("select.*isbn,.*quantity.*", result);
List orderList = new ArrayList();
orderList.add("1234567890");
orderList.add("1111111111");
Bookstore.order(getJDBCMockObjectFactory().getMockConnection(), orderList);
verifySQLStatementExecuted("select.*isbn,.*quantity.*\\(isbn='1234567890'.*or.*isbn='1111111111'\\)");
}
From this, I surmise that it's using standard Java regex syntax. In which case, you probably want:
prepareResultSet("select \\* from table where userId in \\(.*\\)", campaignsResult);
...or perhaps more succinctly (and depending upon exactly how fine-grained your tests need to be):
prepareResultSet("select .* from table where userId in .*", campaignsResult);
The main caveat to be aware of when enabling the regex matching is that any literal special characters that you want in your query (such as *, (, and ) literals) need to be escaped in your regex before it will work properly.
I have a query written to run on an Oracle database which uses the function REGEXP_LIKE to filter some rows from the query. The specific function call is
regexp_like(col1, '[^[:alpha:]]')
The problem is when I run the query on H2 I get the following error:
org.h2.jdbc.JdbcSQLException: Function "REGEXP_LIKE" not found
If I run the query directly on the Oracle database using the SQLDeveloper tool it returns as expected.
Any ideas what could be causing this?
See the excellent documentation.
col REGEXP '[^[:alpha:]]'
In general SQL variants either use a function or named operator.
Whether the above specific regex works I do not know. One should be able to rely on java regular expressions.
H2 doesn't have a function called regexp_like. But you could create one using a user defined function:
create alias regexp_like as
$$ boolean regexpLike(String s, String p) { return s.matches(p); } $$;
drop table test;
create table test(id int, name varchar(2555));
insert into test values(1, 'Steven');
insert into test values(2, 'Stefan');
select * from test where regexp_like(name, '^Ste(v|ph)en$');
REGEXP_LIKE was added to h2 as of Version 1.4.193 (2016-10-31)
http://h2database.com/html/functions.html?#regexp_like
https://github.com/h2database/h2database/pull/323
Here is a slightly improved version of the H2 user function by Thomas Mueller which supports flags and NULL values:
create alias regexp_like as
$$ boolean regexpLike(String s, String p, String flags) {
if(null == s) return false;
if(null != flags) { p = "(?" + flags + ")" + p; }
java.util.regex.Pattern compiled = java.util.regex.Pattern.compile(p);
return compiled.matcher(s).find();
} $$
https://h2database.com/html/grammar.html#regexp_predicate_right_hand_side
Regular expression matching is used. See Java Matcher.find for details. Example: REGEXP '[a-z]'
https://overcoder.net/q/8528/%D1%80%D0%B0%D0%B7%D0%BD%D0%B8%D1%86%D0%B0-%D0%BC%D0%B5%D0%B6%D0%B4%D1%83-match-%D0%B8-find-%D0%B2-java-regex
Matches returns true if the entire string matches the given pattern. find tries to find a substring that matches the pattern
Matches (p) is the same as find ("^" + p + "$")
Sampl:
DELETE FROM sampledb.user_t WHERE email REGEXP '^[a-zA-Zа-яА-Я0-9 .-]+$';
I'm writing a simplified SQL parser that's using regexes to match each valid command. I'm stuck on matching the following:
attribute1 type1, attribute2 type2, attribute3 type3, ...
Where attributes are names of table columns, and types can be a CHAR(size), INT, or DEC. This is used in a CREATE TABLE statement:
CREATE TABLE student (id INT, name CHAR(20), gpa DEC);
To debug it, I'm trying to match this:
id INT, name CHAR(20), gpa DEC
with this:
(?<attributepair>[A-Za-z0-9_]+ (INT|(CHAR\([0-9]{1,3}\))|DEC))(, \k<attributepair>)*
I even tried it without naming the backreference:
([A-Za-z0-9_]+ (INT|(CHAR\([0-9]{1,3}\))|DEC))(, \1)*
I tested the latter regex expression with regexpal and it matched, but both don't when I try it in my Java program. Is there something I'm missing? How can I make this work? Perhaps this has something to do with how I'm calling Pattern.compile(), like if I'm missing a flag or not. I'm also have JDK v7.
Update: I've found that although matches() returns false, lookingAt() and find() return true. It's matching each individual attribute. I want to craft my regex so it matches the whole expression rather than each attribute.
There is no "match as many time as possible and join all the groups together" in Java.
You either have to do it yourself using:
while(matcher.find()) {
// ...
}
... or using a regex that already matches everything in a single call to find.
For example, you could try the following regex (as Java String) instead, which will match all your attributes at once.
(?:\\w+ (?:INT|CHAR(?:\\(\\d{1,3}\\))?|DEC)(?:, )?)+
Here is a working example:
final String str = "CREATE TABLE student (id INT, name CHAR(20), gpa DEC);";
final Pattern p = Pattern.compile("(?:\\w+ (?:INT|CHAR(?:\\(\\d{1,3}\\))?|DEC)(?:, )?)+");
final Matcher m = p.matcher(str);
if(m.find()) {
System.out.println(m.group()); // prints "id INT, name CHAR(20), gpa DEC"
};
Output:
id INT, name CHAR(20), gpa DEC
When you do something like ([A-Za-z0-9_]+ (INT|(CHAR\([0-9]{1,3}\))|DEC))(, \1)* the backreference is for what the first group actually matched.
Ie, id INT, id INT, name CHAR(20), gpa DEC would work with the backreference in the sense that id INT, id INT would become part of the same match. (If you stick that in regexpal you'll see the difference quite clearly based on the highlights.)