gpt4 book ai didi

java - 使用 Android 模式和匹配器类(正则表达式)

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:46 26 4
gpt4 key购买 nike

我刚开始使用 Android,但我的实习任务是帮助完成一个项目。

假设我有以下详细信息:

Fonia Taylo
Product Manager

foniataylo@gmail.com
98706886

根据我上面的详细信息,我想将它传递到一个类中,然后我可以使用正则表达式过滤掉电子邮件地址,并将这个过滤出的电子邮件地址传递给 EditText。

我搜索了很多关于正则表达式的教程,尤其是关于 Android Pattern 和 Matcher 类的教程。

但我找到的所有示例仅用于验证仅输入到 EditText 字段中的文本。

我需要做的是:

  1. 如上所示验证整个文本
  2. 使用正则表达式过滤掉电子邮件地址(并删除其余文本)
  3. 将此电子邮件地址传递给 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
}

关于java - 使用 Android 模式和匹配器类(正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34893068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com