0

I need help with my regex so it can find if there is an @ sign within the string I'm searching.

import java.util.regex.*;
public class OnlineNewspaperSubscription extends NewspaperSubscription
{
    public void setAddress(String a)
    {

         address = a;

        // Creating a pattern from regex
        Pattern pattern
            = Pattern.compile("@*");

        // Get the String to be matched
        String stringToBeMatch = a;

        // Create a matcher for the input String
        Matcher matcher = pattern.matcher(stringToBeMatch);

       if(matcher.matches())
        {
            super.rate = 9;

        }
       else
        {
            super.rate = 0;
            System.out.println("Need an @ sign");
        }

    }

}

I should be able to tell whether this string is an email address or not.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • 4
    Why use a regex? You can use `String#contains()` or `String#indexOf()` – Phil Apr 04 '19 at 00:45
  • 1
    Change regex from `"@*"` to `"@"` and change `matches()` to `find()`. – Andreas Apr 04 '19 at 00:46
  • I thought regex would be easier to get this in but I'll try the indexOf –  Apr 04 '19 at 00:47
  • Partly duplicate of [Difference between matches() and find() in Java Regex](https://stackoverflow.com/q/4450045/5221149) – Andreas Apr 04 '19 at 00:53
  • `I should be able to tell whether this string is an email address or not` with the @, yeah sure thing. –  Apr 04 '19 at 01:06
  • "I should be able to tell whether this string is an email address or not." is Select client.name, "@" from Clients an email address? – Scuba Steve Apr 04 '19 at 03:08

2 Answers2

2

You don't need a regular expression to find the index of '@' in a String; use String.indexOf(int) (passing a char). Like,

int p = a.indexOf('@');
if (p > -1) {
    // ...
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You do not need to use regex for this, it is an overkill. You can just use the method contains() from the String class available from java 1.5 (if I remember correctly). This method does actually use internally indexOf().

System.out.println("Does not contain :" + "Does not contain".contains("@"));
System.out.println("Does cont@in :" + "Does not cont@in".contains("@"));

output:

Does not contain @:false
Does contain @:true

Notes:

If what you want to do is validate the format of an email address, checking the presence of an @ is not sufficient, I would recommend using a regex for this.

Example: https://stackoverflow.com/a/8204716/8794221

Allan
  • 12,117
  • 3
  • 27
  • 51