Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching only one occurrence of a character from a given set

Tags:

java

regex

I need to validate an input string such that validation returns true only if the string contains one of the special characters @ # $ %, only one, and one time at the most. Letters and numbers can be anywhere and can be repeated any number of times, but at least one number or letter should be present

For example:

a@ : true

@a : true

a@$: false

a@n01 : true

an01 : false

a : false

@ : false

I tried

 [0-9A-Za-z]*[@#%$]{1}[0-9A-Za-z]*

I was hoping this would match one occurrence of any of the special characters. But, no. I need only one occurrence of any one in the set.

I also tried alternation but could not solve it.

like image 708
Vivek Vardhan Avatar asked May 29 '14 09:05

Vivek Vardhan


1 Answers

I hope this answer will be useful for you, if not, it might be for future readers. I am going to make two assumptions here up front: 1) You do not need regex per se, you are programming in Java. 2) You have access to Java 8.

This could be done the following way:

private boolean stringMatchesChars(final String str, final List<Character> characters) {
    return (str.chars()
            .filter(ch -> characters.contains((char)ch))
            .count() == 1);
}

Here I am:

  1. Using as input a String and a List<Character> of the ones that are allowed.
  2. Obtaining an IntStream (consisting of chars) from the String.
  3. Filtering every char to only remain in the stream if they are in the List<Character>.
  4. Return true only if the count() == 1, that is of the characters in List<Character>, exactly one is present.

The code can be used as:

String str1 = "a";
String str2 = "a@";
String str3 = "a@@a";
String str4 = "a#@a";
List<Character> characters = Arrays.asList('@', '#', '$', '%');

System.out.println("stringMatchesChars(str1, characters) = " + stringMatchesChars(str1, characters));
System.out.println("stringMatchesChars(str2, characters) = " + stringMatchesChars(str2, characters));
System.out.println("stringMatchesChars(str3, characters) = " + stringMatchesChars(str3, characters));
System.out.println("stringMatchesChars(str4, characters) = " + stringMatchesChars(str4, characters));

Resulting in false, true, false, false.

like image 95
skiwi Avatar answered Sep 20 '22 14:09

skiwi