我目前正在尝试做一个商业名片扫描仪应用程序。这里的想法是拍一张名片的照片,它会提取文本并将文本分类到不同的 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”传递给方法的,如下所示:
我还尝试将文本传递给所有三个参数。但是由于该方法是void
,所以无法完成。或者,如果我将方法更改为 String
而不是 void
,它将需要一个返回值。
最佳答案
试试这段代码。该函数接受识别文本并使用断线符号将其拆分。然后运行一个循环并通过运行模式检查来确定内容的类型。每当确定模式时,循环将使用 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.
}
关于java - 使用正则表达式和 android 对不同的字段进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143413/