emadalamoudi
emadalamoudi

Reputation: 357

How to exclude '@' in regular expression

I have a problem related to regular expression that I want to exclude one character but I did not know how.

This is the code:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.*;

class ExtractDemo {
public static void main(String[] args) {
    String input = "From [email protected] Fri Jan 5 09:14:16 2016";

    Pattern p = Pattern.compile("@.*?\\s");
    Matcher m = p.matcher(input);


    while (m.find()) {
        System.out.println("Found a " + m.group() + ".");
    }
}

}

The output is '@gmail.com' However I want to delete '@'. So the output would be 'gmail.com'

I have tried the expression: ("[^@].*?\s") but it did not work :(

Thanks in advance

Upvotes: 2

Views: 83

Answers (1)

Saleem
Saleem

Reputation: 8978

I'd like to write regex as:

public static void main(String[] args) {
    String input = "From [email protected] Fri Jan 5 09:14:16 2016";

    Pattern p = Pattern.compile("(?<=@)(\\w+(\\.\\w+)+)");
    Matcher m = p.matcher(input);

    while (m.find()) {
        System.out.println("Found a " + m.group(1) + ".");
    }
}

I'm checking @ in non capturing block so final output will capture only gmail.com but not gmail..com

Upvotes: 2

Related Questions