如何编辑电子邮件&来自文字的电话信息?

时间:2011-06-15 04:32:38

标签: java regex

是否有正则表达式编辑电子邮件和&来自此文的电话信息:

Hi John,
Please contact me at tom@email.com or 212-555-1212 or 313.555.1313.
Thank you.
Tom

这样就变成了这个:

Hi John,
Please contact me at [REDACTED] or [REDACTED] or [REDACTED].
Thank you.
Tom

2 个答案:

答案 0 :(得分:3)

使用String.replaceAll()。您可以使用此正则表达式来匹配电子邮件地址:

[^@\s]+@[^@\s]+\.[a-zA-Z]{2,}

这个用于电话号码:

\d{3}[-.]\d{3}[-.]\d{4}

可以支持更多种类的电话号码格式,但我只讨论了您问题中的示例。

这是一个小测试程序来证明上述工作:

public class Redacted {
    public static void main(String[] args) {
        String text = "Hi John,\n"
            + "Please contact me at tom@email.com or 212-555-1212 or 313.555.1313.\n"
            + "Thank you.\n"
            + "Tom";
        System.out.println("Before:\n" + text + "\n");
        // replace email addresses
        text = text.replaceAll("[^@\\s]+@[^@\\s]+\\.[a-zA-Z]{2,}", "[REDACTED]");
        // replace phone numbers
        text = text.replaceAll("\\d{3}[-.]\\d{3}[-.]\\d{4}", "[REDACTED]");
        System.out.println("After:\n" + text + "\n");
    }
}

上述程序输出:

Before:
Hi John,
Please contact me at tom@email.com or 212-555-1212 or 313.555.1313.
Thank you.
Tom

After:
Hi John,
Please contact me at [REDACTED] or [REDACTED] or [REDACTED].
Thank you.
Tom

答案 1 :(得分:-1)

java.util.regex.MatcherreplaceAll方法。