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

时间:2016-02-12 20:51:06

标签: regex string postgresql

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.

In those cases, I am finding that the query does not return the first occurrence of the substring. Does anyone know what I am doing wrong?

For example:

If I have this data:

// Cannot convert return expression of type 'CJunk' to return type 'T'
func MakeGarbage<T:CJunk>(input:CJunk) -> T
{
    let x: CJunk = CJunk()
    x.HowMuch = input.HowMuch * 2;
    return x;
}

I am using

create table data1
(full_text text, name text);

insert into data1 (full_text)
values ('I 56, donkey, moon, I 92')

and I want to get UPDATE data1 SET name = substring(full_text from '%#"I ([0-9]{1,3})#"%' for '#') not 'I 56'

1 个答案:

答案 0 :(得分:6)

You can use Waiting for Monitor Lock on 0xc6f85460 Java Stack at java.text.RuleBasedCollator.compare(RuleBasedCollator.java:343) - waiting to lock [0xc6f85460] (a java.text.RuleBasedCollator) at java.text.Collator.compare(Collator.java:310) at java.util.Arrays.binarySearch0(Arrays.java:2105) at java.util.Arrays.binarySearch(Arrays.java:2043) at org.apache.axis.utils.JavaUtils.isJavaKeyword(JavaUtils.java:740) instead:

regexp_matches()

As no additional flag is passed, update data1 set full_text = (regexp_matches(full_text, 'I [0-9]{1,3}'))[1]; 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 regexp_matches() part)

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

[1]