Extraer texto entre etiquetas en una cadena simple

I cannot seem to grasp the whole concept of regular expressions, I've been working with php for a couple years now and have, for the most part, tried to avoid the preg_match and such functions. I was wondering if you guys could point me in the right direction to where I might be able to learn regex for java, or just regex in general? I've tried numerous different tutorials and guides and I am still having trouble.

In the mean time while I am trying to learn and improve my regex skills, can you guys help me with this?

in java I have a string that is like so

String secKey;
secKey = "<auth_key>5aff0b2449511aac46e14b5e62436e994c5d</auth_key>";

How would I go about extracting just "5aff0b2449511aac46e14b5e62436e994c5d" from the string?

If you guys could help me with that and possibly point me in the right direction to get me on the right track with regex that would be great, Thanks!

preguntado el 28 de agosto de 11 a las 01:08

m{<auth_key>(.+)</auth_key>}. But I'd not use regular expressions here, but Commons Lang StringUtils substringBetween. -

Be forewarned: Regex has to be one of the absolute worst tools to use to parse xml-like text. -

Be aware that @Thilo's example is using Perl notation, which won't work in Java. See mazaneicha's answer for how you would write the regex in Java source code. -

3 Respuestas

Algo como esto:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class X {
        . . .
    public static String extractValue(String s) {
      Pattern p =  Pattern.compile("<auth_key>(.+)</auth_key>") ;
      Matcher m = p.matcher(s) ;
      if ( m.find()) 
          return m.group(1) ;
      else
         return null ;
    }
        . . .
}

Respondido 28 ago 11, 08:08

I started learning regex from this SO post. Aprender expresiones regulares As a learning tool as well as testing ground for current works on regex, I used to use http://rubular.com/ . I hope this will give you a head start.

contestado el 23 de mayo de 17 a las 13:05

Regular expressions in java using java.util.regex.Patternenlace

Regular expressions Tutorial enlace

Respondido 28 ago 11, 12:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.