6

I want to replace data after numbers with '' using regex_replace.

For example:

input --> output
MA0244891-D --> MA0244891
MA0244891 --> MA0244891
MA0244891D --> MA0244891
0244891D --> 0244891

I tried a few regex_replace as below:

REGEXP_REPLACE(rk.mystring, '[^0-9]+', '')) --> only get numbers
REGEXP_REPLACE(rk.mystring, '[^a-zA-Z0-9]+', '')) ---> get alphanumeric including the last characters
REGEXP_REPLACE(rk.mystring, '[^a-zA-Z][^0-9]+', '')) ---> almost correct but truncate numbers at the back

Appreciate your kind help

4
  • 1
    To remove anything after last digit: REGEXP_REPLACE(mystring, '(.*\\d).*', '$1') Commented Jun 30, 2022 at 10:22
  • AAA111BBB222CCC --> ? Commented Jun 30, 2022 at 10:33
  • 1
    @bobblebubble i have tried and it works! tqvm Commented Jul 1, 2022 at 1:10
  • You have recently obtained voting privileges, kindly upvote the answers (see how) that you like. Commented Jul 7, 2022 at 20:39

2 Answers 2

3

You can remove any non-alphanumeric in the string and any letters at the end of string:

REGEXP_REPLACE(rk.mystring, '[^0-9A-Za-z]|[a-zA-Z]+$', '')

See the regex demo.

Details:

  • [^0-9A-Za-z] - any char other than ASCII digits and letters
  • | - or
  • [a-zA-Z]+$ - one or more ASCII letters at the end of string.
Sign up to request clarification or add additional context in comments.

1 Comment

i have tried the answer and it works! tqvm
1

You may replace on the pattern -?[A-Z]$:

SELECT REGEXP_REPLACE(mystring, '-?[A-D]$', '') AS mystring_out
FROM yourTable;

Here is a running SQL demo.

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.