Regex to pick a text between <>

Asked

Viewed 9,178 times

1

  • 3

    What language are you using?

  • Depending on the language, it is better to use normal string operations instead of Regex.

  • @Bacco Using Java.

4 answers

4

Alternative solution (without Regex)

As the author mentioned being using Java, there is an alternative answer with substring, for those who might be interested:

mail = mail.substring(mail.indexOf("<")+1,mail.indexOf(">"));

See working on IDEONE.

2

You can use an expression that reads all characters other than the >:

\<([^\>]+)\>

A Jsfiddle showing an example with this regex: http://jsfiddle.net/r1mfz24s/. Note that you don’t need to escape the < and the >, but I usually escape all the special characters to avoid confusion.

1

  • I don’t know if AP has strings with multiple emails but if it has this regex it will fail https://regex101.com/r/uV1tQ7/1

  • 1

    @Sergio Sim, but then the AP should specify right what it will receive or not.

  • 2

    Yes, the question has this flaw and still does not specify the language. Let’s see if the AP edits and adds more info. (ah, I saw now that is in the comments)

1


Does anyone know how to remove the <>?

Yes, you have to escape them.

Java...

public static void main(String[] args) {

    String texto = "Joao <[email protected]>";
    String regex = "\\<(?<meuGrupo>.*?)\\>";
    String retorno = "";

    Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);;
    Matcher comparator = pattern.matcher(texto);
    if (comparator.find(0)){
        retorno = comparator.group("meuGrupo");
    }

    System.out.println(retorno);
}
  • Good solution! Used regex and language features. Code was good. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.