Using Android Pattern and Matcher class (Regex)

17,462

Solution 1

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
}

Solution 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
}
Share:
17,462
Daniel Louis
Author by

Daniel Louis

Updated on June 04, 2022

Comments

  • Daniel Louis
    Daniel Louis almost 2 years

    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
    
    [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 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!

  • Daniel Louis
    Daniel Louis over 8 years
    Thank you so much for your reply~ I will test it out :D
  • Daniel Louis
    Daniel Louis over 8 years
    Hi @kris larson, do I replace "inputString" with "textToUse"?
  • kris larson
    kris larson over 8 years
    Yes, whatever has the string with the email embedded in it somewhere.
  • Daniel Louis
    Daniel Louis over 8 years
    I have found a similar answer to your's: stackoverflow.com/questions/4662215/…. 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
  • kris larson
    kris larson over 8 years
    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.