2

I have a String coming in like this -

ABC;ABC;XYZ;PQR;ABC;PQR

And requirement is to convert this to something like this -

ABC;XYZ;PQR

Meaning a Regex should keep all Unique words and remove duplicates. Can anyone please help me with this. Is this possible in SQL?

4
  • (1) Tag your question with the database you are using. (2) Fix your data structure. Storing values in string lists is not the SQLish way to store things. Commented Jul 3, 2017 at 11:31
  • (1) what Database Access Language you are using (2) which database -> MySQL or Commented Jul 3, 2017 at 11:33
  • (1) Are you using PHP or what> Commented Jul 3, 2017 at 11:34
  • I'm on HP Vertica. I wrote a piece but its not working as expected- SELECT REGEXP_REPLACE('ABC;PQR;ABC','^(.+?)\;\1*$','\1') Commented Jul 3, 2017 at 11:35

2 Answers 2

2

Since HP Vertica uses PCRE regex, the following regex (with null replacement) should work:

(?<=\;|^)(.+?)\;(?=(.+\;)?\1(\;|$))

See demo.

Followe a brief explanation:

  • (?<=\;|^) is a positive lookbehind meaning that (.+?)\; to remove should be preceded by a semicolon or the begin of string
  • (.+?) is the first capturing group
  • (?=) is a positive lookahead containing:
    • (.+\;)? any other character (ending with a semicolon)
    • \1 backreference for the first capturing group
    • (\;|$) must end with semicolon or EOL
Sign up to request clarification or add additional context in comments.

Comments

-1

With T-Sql you could do:

    DECLARE @Strings NVARCHAR(MAX);
    SET @Strings = '';
    SELECT @Strings = CASE WHEN @Strings != '' THEN @Strings + ';' + [String] ELSE [String] END
    FROM (
        SELECT DISTINCT VALUE AS [String] FROM STRING_SPLIT( 'ABC;ABC;XYZ;PQR;ABC;PQR',';')
    ) AS [Strings]; 
    SELECT @Strings

1 Comment

Thanks for responding but T SQL is not in option. I want to achieve it from a Regex if possible.

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.