我正在尝试将文本输出传递给正则表达式方法,我可以将整个文本输出并提取出电子邮件地址。
例如,我的文本输出如下:
Taria Joseph
General Manager
96523325
tariajoseph@hotmail.com
我想将上面的文本输出传递给正则表达式方法并提取出“tariajoseph@hotmail.com”并显示为EditText。
以下是我的代码:
public class CreateContactActivityOCRtest extends Activity {
private String recognizedText, textToUse;
private EditText mEditText1, mEditText2;
private String mFromLang, mCurrentLang;
private Pattern pattern;
private Matcher matcher;
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,})$";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createcontact);
// Getting the path of the image to show
Bundle extras = this.getIntent().getExtras();
recognizedText = extras.getString("TEXT");
textToUse = recognizedText;
// Getting the language used for text recognition
mFromLang = extras.getString("LANG");
mCurrentLang = mFromLang;
//Log.i(TAG, mFromLang);
textToUse = EmailValidator();
setupUI();
}
public String EmailValidator() {
String email = textToUse;
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;
}
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
public void setupUI(){
// Setting up the textbox
mEditText1 = (EditText)findViewById(R.id.EmailET);
mEditText2 = (EditText)findViewById(R.id.role);
mEditText1.setText(textToUse);
mEditText2.setText(textToUse);
}
}
我想做的是:
EmailValidator()
(不确定我是否正确)EmailValidator()
获取输出并将其传递给setupUI()
(未完成)有人可以帮我查看出错的部分吗?是我的正则表达式方法(EmailValidator()
)中的方法或错误的传递吗?
目前,在设备上进行测试时,页面会立即显示 整个 文本输出到EditText。
答案 0 :(得分:0)
您可以查看电子邮件验证Here。更改您的代码,如下所示
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createcontact);
mEditText1 = (EditText)findViewById(R.id.EmailET);
mEditText2 = (EditText)findViewById(R.id.role);
Bundle extras = this.getIntent().getExtras();
if (extras != null) {
recognizedText = extras.getString("TEXT");
mFromLang = extras.getString("LANG");
textToUse = recognizedText;
mCurrentLang = mFromLang;
// textToUse = EmailValidator(textToUse);
if(isValidEmail(recognizedText))
{
textToUse=recognizedText
}
else
{
//this is invalid email part
}
setupUI();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public void setupUI(){
mEditText1.setText(textToUse);
mEditText2.setText(textToUse);
}