首页 > 解决方案 > 正则表达式在字符串中查找 @ 符号

问题描述

我需要我的正则表达式帮助,以便它可以找到我正在搜索的字符串中是否有 @ 符号。

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

    }

}

我应该能够判断这个字符串是否是电子邮件地址。

标签: javaregex

解决方案


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) {
    // ...
}

推荐阅读