Question

Je suis en train d'écrire un petit programme Java qui accepte un fichier (en utilisant la classe du scanner), retournez le fichier en tant que chaîne, puis recherchez cette chaîne pour une instance d'une sous-chaîne commençant par « E-mail: » et se terminant par ".edu". Il y aura de nombreux cas de cette sous-chaîne, que je veux chacun pour analyser sortir dans un tableau ou un nouveau fichier.

Je sais comment trouver une sous-chaîne, mais je ne sais pas comment A) rechercher toutes les instances de la sous-chaîne et B) préciser le début et la fin de la sous-chaîne.

Quelqu'un peut-il me aider avec cette logique?

Merci!

Était-ce utile?

La solution

Cela ressemble à un cas pour les expressions régulières pour moi:

import java.util.regex.*;

public class Test
{
    private static final Pattern EMAIL_PATTERN = Pattern.compile
        ("Email:(.*?\\.edu)");

    public static void main(String[] args)
    {
        String testString = "FooEmail:jjj@xyz.edu Bar Email:mmm@abc.edu Baz";

        printEmails(testString);
    }

    public static void printEmails(String input)
    {
        Matcher matcher = EMAIL_PATTERN.matcher(input);
        while (matcher.find())
        {
            System.out.println(matcher.group(1));
        }
    }
}

Notez que vous obtiendrez des résultats étranges si vous avez des non emails .edu là ... par exemple, si vous avez « Email: foo@bar.com Email: a @ b. edu » tu finirais avec un match de "foo@bar.com Email:. a@b.edu"

Autres conseils

Vous pouvez utiliser indexOf (). Je pense que vous pouvez dire où chercher de trop. Donc, pour trouver vos instances de "Email:":

while(index < input.size()){
  substringLocation = input.indexOf("Email:", index);
  // do something with substring
  index = substringLocation;
}
private static final Pattern EMAIL_PATTERN = Pattern.compile
    ("Email:(.*?\\.[a-z]*?[\\.[a-z]]*)"); 

résoudra le problème et itt fonctionnera pour tout motif e-mail tels que abc.co.in xyz.com ou domaines test.fileserver.abc.co.bz.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top