Imran khan
Imran khan

Reputation: 857

Regular expression , Limit the special character occrance

I am new to regular expression, I am trying to write regular expression, which take all alphanumeric value and special character as '#' only one occurrence)

List<String> names = new ArrayList<String>();
        names.add("GSDAHA");  
        names.add("AGE2");  
        names.add("257#ASDF");  
        names.add("302#JBMTU#");  //Incorrect
         
        String regex = "^(?!(.*#){1})^[a-zA-Z0-9#]*$";
        
         
        Pattern pattern = Pattern.compile(regex);
         
        for (String name : names)
        {
          Matcher matcher = pattern.matcher(name);
          System.out.println(matcher.matches());
        }

OutPut
    GSDAHA=> true
    AGE2 => true
    257#ASDF => true
    302#JBMTU# => false //2 occurrence of #
    ABC<DE => false    // < special character
   

Upvotes: 1

Views: 37

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

You can use

String regex = "\\p{Alnum}+(?:#\\p{Alnum}+)?";
String regex = "[A-Za-z0-9]+(?:#[A-Za-z0-9]+)?";

Both patterns match one or more alphanumeric chars and then an optional occurrence of a # and then one or more alphanumeric chars.

NOTE: If there can be no alphanumeric chars before # and after, use * quantifier (zero or more occurrences) instead of + (one or more occurrences).

See the Java demo:

List<String> names = new ArrayList<String>();
    names.add("GSDAHA");  
    names.add("AGE2");  
    names.add("257#ASDF");  
    names.add("302#JBMTU#");  
    names.add("ABC<DE");
String regex = "\\p{Alnum}+(?:#\\p{Alnum}+)?";
Pattern pattern = Pattern.compile(regex);
         
for (String name : names)
{
    Matcher matcher = pattern.matcher(name);
    System.out.println(name + " => " + matcher.matches());
}

Output:

GSDAHA => true
AGE2 => true
257#ASDF => true
302#JBMTU# => false
ABC<DE => false

Upvotes: 1

Related Questions