How to create variable pattern matching for database lookup?

I'd like to find a table row where the desired value has the form of A9-B19-C12-D1. Thus, variable letters followed by variable digits, devided by - each. The length is not fixed, eg it could also be only A9 or A9-D1.

I only care about the letters. Now I have the 4 letters A, B, C, D and I want to run a query against postgres db that there is an entry in the format above.

Would I do this with the following statement?

SELECT * FROM mytable t WHERE t.entry LIKE 'A%B%C%D%';

If this is correct: how could I formulate a NamedQuery where I could provide the letters as variable parameters?

Answers


Try using SIMILAR TO with a reqular expression A\d+(-B\d+(-C\d+(-D\d+)?)?)?

@NamedNativeQueries({
    @NamedNativeQuery(
    name = "finDesiredData",
    query = "select * from mytable t where t.entry SIMILAR TO :ent",
        resultClass = MyTable.class
    )
})

I would personally use java StringBuffer to concatenate letters into a correct regexp.


You can try using the regexp_replace function in PostgreSQL. Essentially, using select regexp_replace('A9-B19-C12-D1', '[0-9]|-', '','g') as letters returns a string which is ABCD.

Similarly, select regexp_replace('A9-D1', '[0-9]|-', '','g') returns AD.

Using this information you can write your queries conditioned on the regexp_replace function output. i.e., SELECT * FROM mytable t WHERE regexp_replace(t.entry, '[0-9]|-', '','g')='ABCD' ;.

I belive you can index a table column on its function output too - but I will leave that for you to research. You could also look at using SQL Functions Returning Sets user-defined functions (I think this is what you mean by named queries).

See SQL Fiddle example


Hmmm, i dont know if i understand your question, but you can set the namedQuery like this:

query.setParamter("param1", "%" + 9 + "%");
query.setParamter("param2", "%" + 1 + "%");

Need Your Help

ASP.NET Project and IE10 Compatibility Mode issues in Windows 7

c# asp.net windows internet-explorer-10

I have an asp.net website that is used by many clients just fine. I recently had a customer who switched to Win7 and IE10. He tells me that whenever he tries to view my site that he is prompted for