Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolate string starting before specific string

My string is as follows:

'NAME NAME NAME 400ML NAME CODE'

I need to identify ML, go left to catch all digits before that and stop on first space to get:

400ML

Current code I have:

 SUBSTR(FIELD,CHARINDEX('ML',FIELD), 2)
like image 697
marcin2x4 Avatar asked Apr 06 '26 17:04

marcin2x4


2 Answers

I suggest using

regexp_substr(field, '\\d+\\s*ML\\b')

This regex will make sure the ML is matched as a whole word, and if there are any whitespaces between a number and ML, they will also be matched.

See the regex demo.

Regex details

  • \d+ - 1 or more digits
  • \s* - 0 or more whitespaces
  • ML - a string ML
  • \b - a word boundary.
like image 73
Wiktor Stribiżew Avatar answered Apr 09 '26 06:04

Wiktor Stribiżew


You can use regexp_substr():

select regexp_substr(field, '[^ ]+ML')

Or for specifically alphanumeric characters:

select regexp_substr(field, '[a-zA-Z0-9]+ML')

If Snowflake is not greedy (which seems unlikely but is possible), then you can do:

select trim(regexp_substr(' ' || field, ' [a-zA-Z0-9]*ML'))
like image 27
Gordon Linoff Avatar answered Apr 09 '26 07:04

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!