Ensuring that a number is present in a string?

1 次查看(过去 30 天)
I am writing a code that asks a user for a password, and it must satisfy the following conditions:
- at least 8 characters in length,
- have at least one capital letter, and one lowercase
- include a number
I have the top two figured out but I don't know how to write a function for the third. It is all in a "while" loop and a value of 1 is assigned to each condition... When all 3 are met, the "while" loop stops repeating.
How can I write the function that will determine if there is a number in the password the user inputs?
Thanks for the help!
  1 个评论
Andy
Andy 2014-4-10
编辑:Andy 2014-4-10
RE:
I am hoping to do something similar to what I did for the function that ensures a capital letter is present in the string. It will look better when written out similarly, in my opinion. Here is what I did for that function:
function [CAPS_check]=CAPS_check(password)
%CAPS_check ensures there is at least one capital letter in the password
%all(lower(password)==password) equal to one, then function has at least one CAP
CAPS_check=all(lower(password)==password);
end

请先登录,再进行评论。

采纳的回答

Andrew Newell
Andrew Newell 2014-4-10
编辑:Andrew Newell 2014-4-10
This can be solved nicely using MATLAB regular expressions. The idea is to look ahead from the start of the line to see if each of the criteria are met, and then to return any strings that match these criteria. If an empty string is returned, it is not a valid password.
function tf = isValidPasswd(str)
anchorToStartOfLine = '^';
atLeastEightChars = '(?=.{8,})'; % I'm assuming that any characters are allowed
atLeastOneLC = '(?=.*?[a-z])';
atLeastOneUC = '(?=.*?[A-Z])';
atLeastOneDigit = '(?=.*?\d)';
matchAll = '.*';
passwdCriteria = [anchorToStartOfLine,atLeastEightChars,atLeastOneLC,atLeastOneUC,atLeastOneDigit,matchAll];
tf = ~isempty(regexp(str,passwdCriteria,'once'));
  2 个评论
Andy
Andy 2014-4-10
Thanks for the help! I was able to use what you did for "atleastOneDigit" and turn it into a function to satisfy the assignment. This is actually part of my homework assignment but I couldn't for the life of me figure it out. Thanks again!!
Andrew Newell
Andrew Newell 2014-4-10
Andy, I'm glad to hear that you made your own version for the assignment.

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2014-4-10
all(lower(password)==password) implies no capital letters. It does not, however, establish that any lowercase letters were used: the password might contain no alphabetic letters at all.
any(password >= '0' & password <= '9') is one of the ways to check for digits.
You should be considering using regexp() instead of looping.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by