0

I need one regular expression pattern, in that i have to verify string contains at least one upper or lower case character or one number i dont have problem with position. if string contains only special charactors it will be invalid. EX :

  • @#@#@# - invalid string
  • !@$%^&a - valid string
  • !@$$*)(&A - valid string
  • !@$$*)(&1 - valid string

What pattern will work here?

String regExp = '([a-zA-Z0-9]*)';

String[] regExps = new string[]{'@#@#@#','@#@#@#a ','@#@#@#A','@#@#@#1'};



    for(string regEx : regExps)

{

    //system.debug('regEx== '+regEx);

    Matcher m = Pattern.compile(regExp).matcher(regEx);



    if(m.matches()) {

        System.debug(regEx);

    }

}
1
  • Please do not apply tags which have nothing to do with your question.
    – Adrian Larson
    Commented Nov 17, 2017 at 3:08

1 Answer 1

2

Please note from the documentation on the Matcher class that the matches method tells you if the pattern matches the entire string:

matches()
Attempts to match the entire region against the pattern

So you are checking if the input sequence consists of only the character class you specify. You want instead to see if that character class appears at any point within the input sequence. You are looking for the find() method:

find()
Attempts to find the next subsequence of the input sequence that matches the pattern. This method returns true if a subsequence of the input sequence matches this Matcher object's pattern.

Your snippet rewritten:

Pattern myPattern = Pattern.compile('[a-zA-Z0-9]');

String[] inputs = new String[]{'@#@#@#','@#@#@#a ','@#@#@#A','@#@#@#1'};
for(String input : inputs)
    if(myPattern.matcher(input).find())
        system.debug(input);

You could also verify your expected behavior according to your bullet list:

Pattern isValid = Pattern.compile('[a-zA-Z0-9]');
system.assert(!isValid.matcher('@#@#@#').find());
system.assert(isValid.matcher('@#@#@#a ').find());
system.assert(isValid.matcher('!@$$*)(&A').find());
system.assert(isValid.matcher('@#@#@#1').find());
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .