使用Android Pattern和Matcher类(Regex)

时间:2016-01-20 06:35:27

标签: java android regex android-intent android-edittext

我刚刚选择了Android,但我的任务是帮助我实习的项目。

让我说我有以下详细信息:

Fonia Taylo
Product Manager

foniataylo@gmail.com
98706886

根据我上面的详细信息,我想将其传递给一个类,然后我可以使用正则表达式过滤掉电子邮件地址,并将此过滤后的电子邮件地址传递给EditText。< / p>

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

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

我需要做的是:

  1. 验证如上所示的整个文本
  2. 使用正则表达式过滤掉电子邮件地址(并删除其余文本)
  3. 此电子邮件地址传递给EditText
  4. 目前以下是我的班级:

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

    正如您所看到的,它几乎是不完整的。我想传递&#34; textToUse&#34;进入正则表达式验证,然后继续执行上述功能。

    编辑:

    按照以下方法:

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

    提取出电子邮件地址;然后,我如何通过意图将此提取的电子邮件地址传递给另一个类中的 EditText

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

3 个答案:

答案 0 :(得分:3)

以下是一些提取与模式匹配的文本的代码:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        [formatter setGroupingSeparator:@"-"];
        [formatter setGroupingSize:4];
        [formatter setUsesGroupingSeparator:YES];

        NSString *num = textField.text ;
        num= [num stringByReplacingOccurrencesOfString:@"" withString:@"-"];
       NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
        textField.text=str;
        NSLog(@"%@",str);

        return textField.text.length <=19;

答案 1 :(得分:1)

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

  • 电子邮件地址:

    android.util.Patterns.EMAIL_ADDRESS
    

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

String target = "";

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

}

答案 2 :(得分:0)

首先,您可以通过创建一个单独的类来将Web内容下载到您的android工作室日志中:

公共类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;
    }
}

然后在onCreate方法中使用此类并下载内容==&gt;在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)) ;
    }
}