4

I have just picked up Android, but am tasked to help with a project for my internship.

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.

I have searched many tutorials on regex, especially on Android Pattern and Matcher classes.

But all the examples I have found are only for validation for the text entered into an EditText field only.

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

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.

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?

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel Louis
  • 63
  • 1
  • 1
  • 6

3 Answers3

5

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
}
kris larson
  • 30,387
  • 5
  • 62
  • 74
  • Thank you so much for your reply~ I will test it out :D – Daniel Louis Jan 20 '16 at 07:10
  • Hi @kris larson, do I replace "inputString" with "textToUse"? – Daniel Louis Jan 20 '16 at 07:25
  • Yes, whatever has the string with the email embedded in it somewhere. – kris larson Jan 20 '16 at 07:32
  • I have found a similar answer to your's: http://stackoverflow.com/questions/4662215/how-to-extract-a-substring-using-regex. For that answer, they print out the results. However for my case, after the text is extracted from your method, do you know how can I pass this results into a EditText through intent? I have tried several way but it failed. p.s. sorry for all the questions – Daniel Louis Jan 20 '16 at 09:50
  • Trying to understand "pass results into a EditText through intent". It sounds like you either want to start a new activity with the email or return to the previous activity with the email. It looks like you know how to start an activity. If you want to return the email to the previous activity, you need to look at how `setResult()` and `onActivityResult()` work together. Maybe you should update your question with a little more detail on that part. – kris larson Jan 20 '16 at 15:06
2

In Android SDK, there is a class called android.util.Patterns, in which you can find some useful regex 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
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
0

Simply first you download the Web content to your android studio log by creating a separated class as following :

public class MainActivity extends 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:

@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)) ;
    }
}
Nech
  • 148
  • 5