Postgresql - How do I extract the first occurence of a substring in a string using a regular expression pattern?

后端 未结 1 569
忘了有多久
忘了有多久 2021-01-18 12:31

I am trying to extract a substring from a text column using a regular expression, but in some cases, there are multiple instances of that substring in the string.

I

相关标签:
1条回答
  • 2021-01-18 13:11

    You can use regexp_matches() instead:

    update data1
      set full_text = (regexp_matches(full_text, 'I [0-9]{1,3}'))[1];
    

    As no additional flag is passed, regexp_matches() only returns the first match - but it returns an array so you need to pick the first (and only) element from the result (that's the [1] part)

    It is probably a good idea to limit the update to only rows that would match the regex in the first place:

    update data1
      set full_text = (regexp_matches(full_text, 'I [0-9]{1,3}'))[1]
    where full_text ~ 'I [0-9]{1,3}'
    
    0 讨论(0)
提交回复
热议问题