Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the first and last occurrences of a specific character inside a string in PostgreSQL

I want to find the first and the last occurrences of a specific character inside a string. As an example, consider a string named "2010-####-3434", and suppose the character to be searched for is "#". The first occurrence of hash inside the string is at 6-th position, and the last occurrence is at 9-th position.

like image 884
MD Sayem Ahmed Avatar asked Jun 03 '10 11:06

MD Sayem Ahmed


People also ask

How do I find the first and last occurrence of a character in a string?

The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .

How do you find the last position of a character in a string in PostgreSQL?

Select position('#' in '2010-####-3434'); will give you the first. If you want the last, just run that again with the reverse of your string.

How do I search for a specific character in a string Postgres?

SUBSTRING() function The PostgreSQL substring function is used to extract a string containing a specific number of characters from a particular position of a given string. The main string from where the character to be extracted.

How do I get the first character of a string in PostgreSQL?

The PostgreSQL LEFT() function returns the first n characters in the string.


2 Answers

Well...

Select position('#' in '2010-####-3434');

will give you the first. If you want the last, just run that again with the reverse of your string. A pl/pgsql string reverse can be found here.

Select length('2010-####-3434') - position('#' in reverse_string('2010-####-3434')) + 1;
like image 143
rfusca Avatar answered Sep 21 '22 20:09

rfusca


My example:

reverse(substr(reverse(newvalue),0,strpos(reverse(newvalue),',')))
  1. Reverse all string
  2. Substring string
  3. Reverse result
like image 34
Tomasz Kozik Avatar answered Sep 18 '22 20:09

Tomasz Kozik