1

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

MOC.OOHAY@ABC.PQRqwertySDdd
MOC.OOHAY@AB.JKLasDDbfn
MOC.OOHAY@XZ.JKGposDDbfn

I want my output to come as

MOC.OOHAY@ABC.PQR
MOC.OOHAY@AB.JKL
MOC.OOHAY@XZ.JKG

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

Uma Kanth
  • 5,659
  • 2
  • 20
  • 41

4 Answers4

1

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

Codebender
  • 14,221
  • 7
  • 48
  • 85
1

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

String s1 = "MOC.OOHAY@ABC.PQRqwertySDdd";
String s2 = "MOC.OOHAY@AB.JKLasDDbfn";
String s3 = "MOC.OOHAY@XZ.JKGposDDbfn";
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.

Siguza
  • 21,155
  • 6
  • 52
  • 89
1

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[]{"MOC.OOHAY@ABC.PQRqwertySDdd","MOC.OOHAY@AB.JKLasDDbfn" , "MOC.OOHAY@XZ.JKGposDDbfn"};
    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:

MOC.OOHAY@ABC.PQR
MOC.OOHAY@AB.JKL
MOC.OOHAY@XZ.JKG
npinti
  • 51,780
  • 5
  • 72
  • 96
0

You can do it like this:

String arr[] = { "MOC.OOHAY@ABC.PQRqwertySDdd", "MOC.OOHAY@AB.JKLasDDbfn", "MOC.OOHAY@XZ.JKGposDDbfn" };
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());
    }
}
Manish Kothari
  • 1,702
  • 1
  • 24
  • 34