简体   繁体   English

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

[英]Using Android Pattern and Matcher class (Regex)

I have just picked up Android, but am tasked to help with a project for my internship.我刚刚选择了 Android,但我的任务是帮助我完成一个实习项目。

Lets say I have the details below:可以说我有以下详细信息:

Fonia Taylo
Product Manager

foniataylo@gmail.com
98706886

From the details I have above, I want to pass it into a class whereby I can then filter out the email address using regex, and pass only this filtered out email address to an EditText.根据我上面的详细信息,我想将它传递到一个类中,然后我可以使用正则表达式过滤掉电子邮件地址,并且将这个过滤掉的电子邮件地址传递给 EditText。

I have searched many tutorials on regex, especially on Android Pattern and Matcher classes.我搜索了很多关于正则表达式的教程,尤其是关于 Android Pattern 和 Matcher 类的教程。

But all the examples I have found are only for validation for the text entered into an EditText field only.但我发现的所有示例仅用于验证输入到 EditText 字段中的文本。

What I need to do is:我需要做的是:

  1. Validate the entire text as shown above如上所示验证整个文本
  2. Filter out the email address using the regex (and delete the rest of the text)使用正则表达式过滤掉电子邮件地址(并删除其余文本)
  3. Pass only this email address to an EditText将此电子邮件地址传递给 EditText

Currently below is my 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();

    }
}

As you can see, it is pretty much incomplete.如您所见,它几乎不完整。 I would like to pass "textToUse" into the regex validation, and then continue to perform the function as stated above.我想将“textToUse”传递给正则表达式验证,然后继续执行上述功能。

Edit:编辑:

After the following method:经过以下方法:

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
        }
        }

which extract out the email address;提取电子邮件地址; How do I then pass this extracted email address to through intent to an EditText that is in another Class ?然后我如何将这个提取的电子邮件地址通过意图传递给另一个 Class中的EditText

Please let me know you how I can change my code if there are any ideas.如果有任何想法,请告诉我如何更改我的代码。 Thank you!谢谢!

Here is some code to extract the text matching the pattern:下面是一些提取与模式匹配的文本的代码:

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
}

In Android SDK, there is a class called android.util.Patterns , in which you can find some useful regex patterns.在 Android SDK 中,有一个名为android.util.Patterns的类,您可以在其中找到一些有用的正则表达式模式。

  • E-Mail Address:电子邮件地址:

     android.util.Patterns.EMAIL_ADDRESS

You can simply use them like this:您可以像这样简单地使用它们:

String target = "";

if (android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()) {
    // valid email address
}

Simply first you download the Web content to your android studio log by creating a separated class as following:只需首先通过创建一个单独的类将 Web 内容下载到您的 android studio 日志中,如下所示:

public class MainActivity extends AppCompatActivity {公共类 MainActivity 扩展 AppCompatActivity {

public class DownloadTsk extends AsyncTask<String, Void, String> {


    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {

                char current = (char) data;

                result += current;

                data = reader.read();
            }

            return result;


        } catch (Exception e) {


            e.printStackTrace();
        } 

        return null;
    }
}

Then you use this class in onCreate method and download the content ==> test it in Log and Finally you use Pattern and Matcher like following:然后在 onCreate 方法中使用此类并下载内容 ==> 在 Log 中对其进行测试,最后使用 Pattern 和 Matcher,如下所示:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DownloadTsk task = new DownloadTsk();
    String result = null;

    try {
        result = task.execute("YOUR WEBSITE ADDRESS..... ").get();

        Log.i("Content", result);


    } catch (Exception e) {
        e.printStackTrace();
    }
    Pattern p = Pattern.compile("WHTEEVER BEFORE(.*?)WHTEEVER AFTER  ");
    Matcher m = p.matcher(result);
    while (m.find()) {
        Log.i("result", m.group(1)) ;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM