Ashish Jain
Ashish Jain

Reputation: 5

Finding Upper Case in String Array and extracting it out

I have an array input like this which is an email id in reverse order along with some data:

[email protected]
[email protected]
[email protected]

I want my output to come as

[email protected]
[email protected]
[email protected]

How should I filter the string since there is no pattern?

Upvotes: 1

Views: 101

Answers (4)

Manish Kothari
Manish Kothari

Reputation: 1712

You can do it like this:

String arr[] = { "[email protected]", "[email protected]", "[email protected]" };
for (String test : arr) {
    Pattern p = Pattern.compile("[A-Z]*\\.[A-Z]*@[A-Z]*\\.[A-Z.]*");
    Matcher m = p.matcher(test);
    if (m.find()) {
        System.out.println(m.group());
    }
}

Upvotes: 0

npinti
npinti

Reputation: 52185

There is a pattern, and that is any upper case character which is followed either by another upper case letter, a period or else the @ character.

Translated, this would become something like this:

String[] input = new String[]{"[email protected]","[email protected]" , "[email protected]"};
    Pattern p = Pattern.compile("([A-Z.]+@[A-Z.]+)");
    for(String string : input)
    {
        Matcher matcher = p.matcher(string);
        if(matcher.find())
            System.out.println(matcher.group(1));
    }

Yields:

[email protected]
[email protected]
[email protected]

Upvotes: 1

Siguza
Siguza

Reputation: 23870

Simply split on [a-z], with limit 2:

String s1 = "[email protected]";
String s2 = "[email protected]";
String s3 = "[email protected]";
System.out.println(s1.split("[a-z]", 2)[0]);
System.out.println(s2.split("[a-z]", 2)[0]);
System.out.println(s3.split("[a-z]", 2)[0]);

Demo.

Upvotes: 1

Codebender
Codebender

Reputation: 14438

Why do you think there is no pattern?

You clearly want to get the string till you find a lowercase letter.

You can use the regex (^[^a-z]+) to match it and extract.

Regex Demo

Upvotes: 1

Related Questions