Marcos J.C Kichel
Marcos J.C Kichel

Reputation: 7219

Regex to select only value inside tags

I have some emails in this format:

name of the person <[email protected]>
name of another person <[email protected]>

I would like to have a regex expression that would select only the elements inside the tags, along with the tags.. the above input would result in this output:

<[email protected]>
<[email protected]>

I would like the regex go work along with Java

Upvotes: 2

Views: 264

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98871

The question as been well answered already, but another option is using <.*?>, i.e:

String text = "name of the person <[email protected]> name of another person <[email protected]>";
Pattern regex = Pattern.compile("<.*?>");
Matcher regexMatcher = regex.matcher(text);
while (regexMatcher.find()) {
    System.out.println(regexMatcher.group(0));
}

Demos:

Java Demo

Regex Demo


Regex Explanation:

<.*?>
    < matches the characters < literally
    .*? matches any character (except newline)
        Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
    > matches the characters > literally

Upvotes: 1

Rion Williams
Rion Williams

Reputation: 76547

You could use the expression <[^>]*> to match everything that was within a single pair of angled braces :

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

// Define your regex
Pattern regex = Pattern.compile("<[^>]*>");
// Get your matches
Matcher m = regex.matcher("{your-input-here}");
// Iterate through your matches
while(m.find()){
    // Output each match
    System.out.println(m.group(0));
}

You can see a working example of this here.

Upvotes: 4

Related Questions