0

我正在尝试提取电子邮件并使用模式(EMAIL_PATTERN)将其替换为空格。运行以下命令时,传入完整文档时不会产生任何输出。该模式将仅匹配整个区域。所以这意味着如果我们只传入电子邮件,电子邮件将被匹配并被替换为空格。但以下方法的目的是查找电子邮件,不需要之前的手动提取。在 tempString 中的电子邮件被替换后,我想将它用于下一个模式。我应该将我想在一种方法中使用的模式组合起来,还是应该将它们放在不同的方法中?以下是我现在拥有的代码。我还有其他模式,但由于我的方法无法正常工作,我还没有发布它们。

private static final String EMAIL_PATTERN = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
public static void main (String[] args) {
//Document takes in a ID, student information(which includes email, address, phone, name),   school, and text   
Document r = new Document("", "FirstName LastName, Address, example@email.com,    phoneNumber", "School", "experience", "text");
            personalEmailZone(r);

 }
public static Document personalEmailZone(Document doc){
    //tempString is the personal information section of a resume
    String tempPI = doc.tempString();
    if(doc.tempString().matches(EMAIL_PATTERN) == true){
        //Pattern pattern = Pattern.compile("");
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(tempPI);
        String emailTemp = "";
        if(matcher.find()){
            emailTemp = matcher.group();
            System.out.println(emailTemp);
            //PI.replace(emailTemp, "");
            System.out.println(emailTemp.replace(emailTemp, ""));
            tempPI = tempPI.replace(emailTemp, "");
            System.out.println(tempPI);
        }
    }
    return doc;
}
4

2 回答 2

0

您可以将模式放置在不同的方法中,这些方法返回修改后的字符串以供文本模式使用。例如

String tempPI = doc.tempString();
tempPI = applyPattern1(tempPI);
tempPI = applyPattern2(tempPI)
tempPI = applyPattern3(tempPI);

您的代码没有显示任何输出,因为doc.tempString().matches(EMAIL_PATTERN) == true. 也许那里不需要它,因为它希望整个字符串都是电子邮件。

于 2012-08-07T16:50:40.400 回答
0

你有几个问题:

public static Document personalEmailZone(Document doc){
    //tempString is the personal information section of a resume
    String tempPI = doc.tempString();
    if(doc.tempString().matches(EMAIL_PATTERN) == true){

上面的语句尝试将整个文档与电子邮件地址模式进行匹配。doc.tempString()除非仅包含一个电子邮件地址而没有其他内容,否则这将不匹配。

        //Pattern pattern = Pattern.compile("");
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(tempPI);
        String emailTemp = "";
        if(matcher.find()){
            emailTemp = matcher.group();
            System.out.println(emailTemp);
            //PI.replace(emailTemp, "");
            System.out.println(emailTemp.replace(emailTemp, ""));

不知道上面是干什么用的。如果您的代码达到这一点,它总是会打印一个空行。

            tempPI = tempPI.replace(emailTemp, "");
            System.out.println(tempPI);
        }

由于没有循环,您将只替换第一次出现的电子邮件地址。如果您希望替换所有事件,则需要循环输入。

    }
    return doc;

At this point you haven't actually modified doc, so you're returning the document in its original form, with email addresses included.

}

Look at the Javadoc for String#replaceAll(String regex, String replacement)

于 2012-08-07T17:52:04.883 回答