Regexp_Replace in HIVE to keep only certain words

Viewed 148

I am trying to use regexp_replace in HIVE as a way to only keep certain words of a string.

I am trying to use the following:

select regexp_replace('I AM WANTING BLUE SHOES AND YELLOW STRINGS', '([^BLUE|SHOES|YELLOW|STRINGS])',' ')

But it is giving me "I W NTING BLUE SHOES N YELLOW STRINGS" instead of "BLUE SHOES YELLOW STRINGS"

I have tried using \b \s and any number of things to no avail. Any tips on getting this to work?

I also considered using regexp_replace but for my particular use case there are too many variables for it to be useful.

1 Answers

You can use

select regexp_replace('I AM WANTING BLUE SHOES AND YELLOW STRINGS', '\\s*\\b(?!(?:BLUE|SHOES|YELLOW|STRINGS)\\b)\\w+','')

See the regex demo

Details

  • \s* - 0+ whitespaces
  • \b - a word boundary
  • (?!(?:BLUE|SHOES|YELLOW|STRINGS)\b) - no BLUE, SHOES, YELLOW and STRINGS substring is allowed immediately on the right
  • \w+ - 1 or more word chars (letters, digits or _)
Related