1

i would like to replace string in my query but only on the end of the string this is my example:

SET @exampleString = 'example_a_chapter_a';

SELECT REPLACE(@exampleString ,'_a','_b1');

Result what I get is this: example_b1_chapter_b1 But i would like this: example_a_chapter_b1

But there can be more time the '_a' in the string as this 'example_a_type_a_chapter_a', but i would like to replace just the end '_a' of the string.

Thanks for you help

2 Answers 2

2

This will be tricky since MySQL can not replace by regex. One of possible ways is:

SELECT REPLACE(REPLACE(CONCAT(@exampleString, '#END'), '_a#END', '_b1'), '#END', '');

-i.e. add something that 100% is not in original string, to it's end and then replace.

Edit: second REPLACE is needed in case if original string doesn't end with _a (so you'll need to remove added #END)

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

1 Comment

In my case there is everytime '_a' on the end
2

You could not use replace() at all. Just reconstruct the string:

select (case when @exampleString like '%_a'
             then concat(left(@exampleString, length(@exampleString) - length('_a')),
                         '_b1'
                        )
             else @exampleString
         end)

This has the advantage that it works even when the string doesn't end in '_a'.

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.