Oct 9, 2013

Query to find the first word from a string

Recently I had a challenge to extract the first word from a string field. For example, I had to extract "Toshiba" from the string field, "Toshiba America Medical Systems" or "California" from the string "California", and so on.

Although, I initially created a CASE-WHEN statement for my query, using SUBSTR and INSTR functionality - which in fact worked just fine, but I kept thinking there must be a better way to handle this.

Sure enough, with a little bit of Google search, I stumbled upon the following link, where the username "jeneesh" showed an example using REGEXP_REPLACE expression to retrieve the same information -- which seemed better one line solution in my opinion:

https://forums.oracle.com/thread/2543764?start=0&tstart=0

So, I just wanted to share the query in case it helps in future.



WITH qry
AS
(
   SELECT NULL field_name FROM dual
      UNION ALL
   SELECT 'Aopu' FROM dual
      UNION ALL
   SELECT 'Abul Mohsin' FROM dual
      UNION ALL
   SELECT 'Abul M Mohsin' FROM dual
      UNION ALL
   SELECT 'Abul M. Mohsin' FROM dual
      UNION ALL
   SELECT 'Princess Cruise Lines, Ltd' FROM dual
      UNION ALL
   SELECT 'Princess Cruise Lines, Ltd.' FROM dual
      UNION ALL
   SELECT 'Princess Cruise Lines Ltd' FROM dual
)
SELECT field_name,
       REGEXP_REPLACE(field_name, '^(\w+)(.*?)(\w*$)', '\1')  exp1,
       REGEXP_REPLACE(field_name, '^(\w+)(.*?)(\w*$)', '\2')  exp2,
       REGEXP_REPLACE(field_name, '^(\w+)(.*?)(\w*$)', '\3')  exp3
  FROM qry;





No comments: