Skip to Main Content
  • Questions
  • function that will return the text between <a> and </a>

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, moin.

Asked: April 11, 2018 - 12:07 pm UTC

Last updated: April 11, 2018 - 3:40 pm UTC

Version: oracle 11g

Viewed 1000+ times

You Asked

Hi tom,

Suppose i have a text like <a>hkjfsdfjashkdfhask_75274_jhsdfbajh</a>

Now i need a pl/sql function in which i will send <a> and </a> as parameters . Then the function will return me the text of above hkjfsdfjashkdfhask_75274_jhsdfbajh .

Means i need the text value between the two given parameter.
Please help.





and Chris said...

Such a simple request... Yet it hides lots of complexity!

- Will the string always start and end with the parameters?

If so can replace them with null:

select replace ( 
         replace(
           '<a>hkjfsdfjashkdfhask_75274_jhsdfbajh</a>', '<a>' 
         ), '</a>'
       ) val
from   dual;

VAL                                  
hkjfsdfjashkdfhask_75274_jhsdfbajh   


- If no, you may be able to flex your regular expression muscles:

select regexp_replace(
         'asdf<a>hkjfsdfjashkdfhask_75274_jhsdfbajh</a>asdf', 
         '(.*)(<a>)(.*)(</a>)(.*)', '\3'
       ) val
from   dual;


- But this (probably) only works if the values you're searching for only appear once in the string. Otherwise this regex always gives the last occurrence:

select regexp_replace(
         'asdf<a>hkjfsdfjashkdfhask_75274_jhsdfbajh</a>asdf<a>here again</a>', 
         '(.*)(<a>)(.*)(</a>)(.*)', '\3'
       ) val
from   dual;

VAL          
here again  


- Is your real requirement to extract values from XML documents based on tags? If so, a little XML processing may be the way to go:

select xmltype('<a>hkjfsdfjashkdfhask_75274_jhsdfbajh</a>').extract('a/text()').getStringVal() val
from   dual;

VAL                                  
hkjfsdfjashkdfhask_75274_jhsdfbajh   


Sooooooo, what's the full requirement here? What are the edge cases and boundary conditions?

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.