Reputation:
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.
Upvotes: 0
Views: 109
Reputation: 12438
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.
Upvotes: 0
Reputation: 201429
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) {
// ...
}
Upvotes: 2