使用正则表达式和android对不同的字段进行分类

时间:2016-02-02 01:16:01

标签: java android regex ocr

我目前正在尝试使用商务名片扫描仪应用。这里的想法是拍一张名片的照片,它会提取文本并将文本分类为不同的EditText。

我已经完成了OCR部分,它从名片图像中提取出所有文本。

我现在缺少的是制作一个正则表达式方法,可以从OCR中提取整个文本,并将名称,电子邮件地址,电话号码分类到EditText各自的字段中。

通过一些谷歌搜索,我已经找到了下面的正则表达式:

private static final String EMAIL_PATTERN =
            "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                    "\\@" +
                    "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                    "(" +
                    "\\." +
                    "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                    ")+";


private static final String PHONE_PATTERN =
            "^[89]\\d{7}$";


private static final String NAME_PATTERN =
            "/^[a-z ,.'-]+$/i";

目前我只是能够使用以下方法提取电子邮件地址:

public String EmailValidator(String email) {

        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);

        if (matcher.find()) {

            return email.substring(matcher.start(), matcher.end());

        } else {

            // TODO handle condition when input doesn't have an email address

        }

        return email;
    }

我不确定如何编辑 ^ above method ^ 以包含一次使用所有3个正则表达式模式,并将它们显示到不同的EditText字段,如(姓名,电子邮件地址,电话号码)。

--------------------------------------------编辑 - - - - - - - - - - - - - - - - - - - - - - - - -

使用@Styx回答后,

它的参数有问题,我用它如何将文本“textToUse”传递给方法,如下所示:

enter image description here

我也尝试将文本传递给所有三个参数。但由于该方法为void,因此无法完成。或者,如果我将方法更改为String而不是void,则需要返回值。

enter image description here

1 个答案:

答案 0 :(得分:4)

试试这段代码。该函数接收识别文本并使用折线符号将其拆分。然后运行循环并通过运行模式检查来确定内容的类型。每当确定模式时,循环将使用 continue 关键字进入下一次迭代。这段代码还能够处理单个名片上出现1个或多个电子邮件和电话号码的情况。希望能帮助到你。干杯!

public void validator(String recognizeText) {

    Pattern emailPattern = Pattern.compile(EMAIL_PATTERN);
    Pattern phonePattern = Pattern.compile(PHONE_PATTERN);
    Pattern namePattern = Pattern.compile(NAME_PATTERN);

    String possibleEmail, possiblePhone, possibleName;
    possibleEmail = possiblePhone = possibleName = "";

    Matcher matcher;

    String[] words = recognizeText.split("\\r?\\n");

    for (String word : words) {
        //try to determine is the word an email by running a pattern check.
        matcher = emailPattern.matcher(word);
        if (matcher.find()) {
            possibleEmail = possibleEmail + word + " ";
            continue;
        }

        //try to determine is the word a phone number by running a pattern check.
        matcher = phonePattern.matcher(word);
        if (matcher.find()) {
            possiblePhone = possiblePhone + word + " ";
            continue;
        }

        //try to determine is the word a name by running a pattern check.
        matcher = namePattern.matcher(word);
        if (matcher.find()) {
            possibleName = possibleName + word + " ";
            continue;
        }
    }

    //after the loop then only set possibleEmail, possiblePhone, and possibleName into
    //their respective EditText here.

}