我刚开始使用 Android,但我的实习任务是帮助完成一个项目。
假设我有以下详细信息:
Fonia Taylo
Product Manager
foniataylo@gmail.com
98706886
根据我上面的详细信息,我想将它传递到一个类中,然后我可以使用正则表达式过滤掉电子邮件地址,并将仅这个过滤出的电子邮件地址传递给 EditText。
我搜索了很多关于正则表达式的教程,尤其是关于 Android Pattern 和 Matcher 类的教程。
但我找到的所有示例仅用于验证仅输入到 EditText 字段中的文本。
我需要做的是:
- 如上所示验证整个文本
- 使用正则表达式过滤掉电子邮件地址(并删除其余文本)
- 仅将此电子邮件地址传递给 EditText
目前下面是我的类(class):
public class RegexOCR1 extends Activity {
private Pattern pattern;
private Matcher matcher;
private String recognizedText, textToUse;
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 from another class
Bundle extras = this.getIntent().getExtras();
recognizedText = extras.getString("TEXT");
textToUse = recognizedText;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.usetext);
showText();
//Log.i(TAG, "onConfigChanged");
}
private void showText(){
//Log.i(TAG, "ShowText");
Intent intent = new Intent(this, CreateContactActivityOCR.class);
startActivity(intent);
}
public EmailValidator() {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(textToUse);
if (matcher.find())
{
String email = textToUse.substring(matcher.start(), matcher.end());
} else {
// TODO handle condition when input doesn't have an email address
}
}
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
如您所见,它还很不完整。我想将“textToUse”传递给正则表达式验证,然后继续执行上述功能。
编辑:
经过以下方法:
public EmailValidator() {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(textToUse);
if (matcher.find())
{
String email = textToUse.substring(matcher.start(), matcher.end());
} else {
// TODO handle condition when input doesn't have an email address
}
}
提取电子邮件地址;然后我如何将这个提取的电子邮件地址通过 Intent 传递给 另一个类 中的 EditText?
如果有任何想法,请告诉我如何更改我的代码。谢谢!
下面是一些提取与模式匹配的文本的代码:
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
String email = inputString.substring(matcher.start(), matcher.end());
} else {
// TODO handle condition when input doesn't have an email address
}
我是一名优秀的程序员,十分优秀!