4

Rather than selecting rows based on whether their string value equals a given regular expression input, I want to select rows with regular expressions that match a given string input.

As far as purpose, I'm am trying to identify website names from input URLs.

TABLE
WEBSITE                    REGEX 
The New York Times         ^.+\.nytimes.com.*$

Is there a good way to do this? I'm using postgres, and I was hoping to avoid large loops.

Thanks!

3
  • 1
    From what I can tell, you should just be able to do SELECT * FROM TABLE where 'http://www.nytimes.com/foo/' ~ REGEX - Though I admit I haven't actually tried it. Commented Jan 24, 2014 at 18:45
  • A simple google search with "postgres regex" shows several results explaining how to do that already among the first few results. Commented Jan 24, 2014 at 18:46
  • Update - Just tried it, works fine.. Posted example below.. Commented Jan 24, 2014 at 18:49

1 Answer 1

1

This seems to work fine:

CREATE TABLE Sites
(
   SiteName text,
   RegEx text  
);

INSERT INTO Sites VALUES ('NY Times', '^.+\.nytimes.com.*$');

Then you can do:

SELECT * FROM Sites
WHERE 'http://www.nytimes.com/Foo' ~ RegEx;

Fiddle

Keep in mind this might start to get slow if you had a lot of rows, as it's going to have to do a sequential table scan each time and run the regular expression against each row. A better approach might be to parse the URL first and normalize it in some way, then look for an exact match in the table.

Sign up to request clarification or add additional context in comments.

3 Comments

I would likely have between 1,000 and 1,500 rows. I need the select output to appear very quickly to end user - it will be initiated via ajax. Do you think this would be "laggy" from UX point of view?
With 1,000 - 1,500? Probably not too bad, computers are pretty fast these days and you can probably wrap it in an IMMUTABLE or STABLE function so everything could be cached.
What would be the MS SQL equivalent of this? I can't find anything related to SQL Server 2012

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.