Home > Software design >  Regex fro fetching the substring after nth _
Regex fro fetching the substring after nth _

Time:03-21

I'm trying to write a regex for getting the substring after the late '_'.

I have written a regex but this is giving me the last '_' as well.

Regex written :

^((?:[^_]*\_){2})

Input string: harmeet_kaur_abc

Regex output: harmeet_kaur_

Required output: harmeet_kaur

CodePudding user response:

You are including the second _ in the repetition.

You could either match only the first part:

SELECT REGEXP_MATCHES('harmeet_kaur_abc', '^[^_]*_[^_]*')

Or remove starting from the last underscore:

SELECT REGEXP_REPLACE('harmeet_kaur_abc', '_[^_]*$', '')

Both will output

harmeet_kaur

CodePudding user response:

SELECT substring('harmeet_kaur_abc' FROM '^(.*)_[^_]*$');

  substring   
══════════════
 harmeet_kaur
(1 row)
  • Related