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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34893068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:31:12  来源:igfitidea点击:

Using Android Pattern and Matcher class (Regex)

javaandroidregexandroid-intentandroid-edittext

提问by Daniel Louis

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

[email protected]
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 onlythis 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 onlythis email address to an EditText
  1. 验证整个文本,如上所示
  2. 使用正则表达式过滤掉电子邮件地址(并删除其余文本)
  3. 将此电子邮件地址传递给 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 EditTextthat is in another Class?

提取电子邮件地址;我如何再经过意图通过这个提取电子邮件地址,向EditText上是在另一个类

Please let me know you how I can change my code if there are any ideas. Thank you!

如果有任何想法,请告诉我如何更改我的代码。谢谢!

回答by kris larson

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
}

回答by frogatto

In Android SDK, there is class called android.util.Patterns, in which you can find various useful regex patterns.

在 Android SDK 中,有一个名为 的类android.util.Patterns,您可以在其中找到各种有用的正则表达式模式。

  • E-Mail Address:

    android.util.Patterns.EMAIL_ADDRESS
    
  • 电子邮件地址:

    android.util.Patterns.EMAIL_ADDRESS
    

Then you can simply use them like this:

然后你可以像这样简单地使用它们:

String target = "";

if(android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()){

}

回答by NEC

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