0

I have strings values such as the following in a column:

|333|,|331|

I want to perform a balanced string replacement as follows:

xxTM_333_TMxx,xxTM_331_TMxx

I have tried to do this with the REPLACE and CONCAT functions but didn't get the desired output.

For example:

SELECT REPLACE('|333|,|331|','|','xxTM');

This replaces one of the | symbols correctly in each case, but not its matched (balanced) counterpart.

How can I achieve this result in MySQL?

4
  • 3
    What did you try exactly? What output did it give? Commented Sep 10, 2013 at 13:35
  • select replace('|333|,|331|','|','xxTM'); Commented Sep 10, 2013 at 13:38
  • You can't do this with built-in functions in MySQL. The problem is that | means something different for every alternative match. You can do this with a regular expression replace, which MySQL doesn't support natively. Do it in your application. Commented Sep 10, 2013 at 13:39
  • select concat(trim(TRAILING 'xxTM' FROM replace(replace('|333|,|331|,|234|','|','xxTM'),'xxTM,xxTM','TMxx,xxTM')),'TMxx'); will output xxTM333TMxx,xxTM331TMxx,xxTM234TMxx Commented Sep 10, 2013 at 14:01

1 Answer 1

3
SET @st := '|333|,|331|';

SELECT
  CASE WHEN @st LIKE '|%|' THEN
    CONCAT(
      'xxTM',
      REPLACE(REPLACE(@st, '|,|', '_TMxx,xxTM_'), '|', '_'),
      'TMxx')
  END rep_st;

Please see fiddle here.

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

Comments

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.