In my application I am accepting a password from the user which should be in following format:-
case sensitive and
must be at least 6 characters long,
including at least
one letter (a-Z),
one number (0-9) and
one of the following special characters:!=+*;:-,._{[()]}#%?#
So by following the tutorial given here:
http://www.mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/
I have created my own pattern as:-
private static final String PASSWORD_PATTERN = "($\\S*(?=\\S{6,})(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*[\\d])(?=\\S*[\\W])\\S*$)";
But it is not working properly. If I enter a correct value for the password as per pattern, it still displays an error to me.
Please tell me what's happening here; what error is there?
Here is my code:-
PWD_Validate = new PasswordValidator();
String password = TXT_PassWord.getText().toString();
if (PWD_Validate.validate(password))
{
}
else{ } it takes me every time in else block, even I entered a correct passwaord.
I'm not sure why you've deviated from the pattern that is listed within the tutorial you've linked. Your pattern starts with $ which asserts position at end of the string, so it's highly unlikely you'll match anything. Usually if you're using an assertion you use $ at the very end of the pattern and ^ to assert the beginning.
Also no where in your pattern do you have any of the special characters you've outlined as those you've said are required. If you plan on matching those I would recommend including them into your pattern.
The breakdown of your regex goes like this:
$ assert position at end of the string (you've got it at the beginning).
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?=\S{6,}) Positive Lookahead - Assert that the regex below can be matched
\S{6,} match any non-white space character [^\r\n\t\f ]
Quantifier: Between 6 and unlimited times, as many times as possible, giving back as needed [greedy]
(?=\S*[a-z]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[a-z] match a single character present in the list below
a-z a single character in the range between a and z (case sensitive)
(?=\S*[A-Z]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[A-Z] match a single character present in the list below
A-Z a single character in the range between A and Z (case sensitive)
(?=\S*[\d]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[\d] match a single character present in the list below
\d match a digit [0-9]
(?=\S*[\W]) Positive Lookahead - Assert that the regex below can be matched
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[\W] match a single character present in the list below
\W match any non-word character [^a-zA-Z0-9_]
\S* match any non-white space character [^\r\n\t\f ]
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string
To be quite honest your regex is so far off from the tutorial you've
linked that it's not even remotely close. I would recommend you go
back and thoroughly re-read and study the guide, for it's apparent you
haven't applied any of it to be applicable by any means.
Related
In my filter used into EditText, I want to be sure the user can only set .5 or .0 for decimal values.
Valid values examples:
34.5
34.0
34
Invalid values examples:
34.2
34.8
34.6
I tried this one, but it doesn't work properly: [0-9]*[.]?[0|5]
Thank you very much guys!
You're probably looking for [0-9]*(\.([50][0]*)*)*.
[0-9]*: Any character from 0 to 9, zero or more times [so that just a "." (= 0.0) input is valid]
\.: You need to escape the '.' character, since it usually would mean "any character", and you especifically need the dot there.
[50][0]*: First, either five or zero (once). Second, the 0 character, zero or more times (since 35.50 = 35.5). This also avoids inputs like 35.59 from being valid, since 9 != 0.
([50][0]*)*: This occurrence zero or more times, so that 35., for instance, becomes a valid input (since 35. = 35.0).
(\.([50][0]*)*)*: As for this grouping, it's in order to check for the five or the zero only if there is a decimal dot. It's grouping the dot character and the 5/0 logic together with a star (zero or more times) at the end, so if it doesn't occur, it still matches.
Let me know if this was what you were looking for.
To verify the whole numbers in the examples, you can make the last part optional and use anchors.
^[0-9]+(?:[.][05])?$
^ Start of string
[0-9]+ Match 1+ digits 0-9
(?:[.][05])? Optionally match . and a digit 0 or 5
$ End of string
See a regex demo.
If you want to be able to only type a pattern like that and also accept empty strings or 34. you can repeat the digit 0 or more times, optionally match . and optionally match either 0 or 5.
^[0-9]*[.]?[05]?$
See another regex demo
I'm try to write a username field validator and one of the reqs is that the field must contain at least 2 numbers (more is ok, just no less). I thought I could do something like this, and the regex splits on the first number, but never on the second.
String[] arr = string.split("[0-9][0-9]");
return arr.length > 2;
Use cases:
Bob11
Bo1b1
11Bob
1Bob1
Below is my version, that has an extremely fast execution, can be easily updated to different criteria, and has a better readability (at least to me):
Regex
(\D*\d){2,}
Example
Bob11 - Match
Bo1b1 - Match
11Bob - Match
1Bob1 - Match
11235 - Match
Bobb - Does NOT Match
Bob1 - Does NOT Match
Bo1b - Does NOT Match
1Bob - Does NOT Match
Explanation
\D - non digit.
* - (quantifier) zero or more times.
\d - one digit.
(\D*\d) - encapsulate the combination above as a group.
{2,} - (quantifier) ensures that the group occurs at least 2 times, being able to occur more times.
(\D*\d){2,} - So, \D* non digit zero or infinite times, followed by a \d digit, this combination repeated {2,} two or infinite times.
Updating to different criteria
The ^ (start string anchor) and $ (end string anchor) can be included to ensure restriction, in case the criteria changes to be exact 2 or any other number.
This is an example that ensures no more, no less that 5 numbers anywhere in a string: ^(\D*\d){5}\D*$. The last \D is necessary to allow the string to end with a non digit, validating the regex if the criteria of five digits be satisfied.*
Try this:
.* matches everything (from 0 to n times)
[0-9] is number from 0-9
Pattern pattern = Pattern.compile("[0-9].*[0-9]");
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
return true;
}
And you can check regex in https://www.freeformatter.com/regex-tester.html
Remove all non numeric characters using regex and count the length
[^\d]*\d[^\d]*\d.* should be one way to go (there are several..)
[^\d]* Matches any character which is not a digit (zero to infinite times)
\d matches a single digit (once)
.* matches everything (zero to infinite times)
I use [^\d]* because .* is greedy and thus might match too much (depending on the language). Greedy behavior can be disabled by appending ?: .*?
You can test it at https://regex101.com/.
You do not need RegEx for this. I'm not sure what language you're using, but it is safe to assume that a String in your language is essentially a Char array. If that is the case, then get the count of digit characters in the Char array and compare if it is greater than 1.
For example, here is a C# example:
String username = Console.ReadLine();
if (username.Count(c => Char.IsDigit(c)) > 1) {
Console.WriteLine("The String contains 2 or more digits.");
} else {
Console.WriteLine("The String did not contain 2 or more digits.");
}
This would likely yield faster results too.
Use string.match(‘.*\d.*\d.*’);
It will look for one digit two times in a string.
I'm new to C and programming in general. I'm stuck wondering why this thing is happening. Basically, I wrote this simple program to input a 6 character array from the user, and to print the same out. I'm using CPPDroid on my Android phone to compile and execute the code;
#include"stdio.h"
int main()
{
char c[6];
for(int i=0;i<=5;i++)
{
scanf("%c",&c[i]);
}
for(int j=0;j<=5;j++)
{
printf("%c",c[j]);
}
return 0;
}
For some reason, the first loop simply exits out before the rest of the elements are filled. I'd get an output like this (I entered a,b,s as the first 3 elements):
a
b
s
a
b
s
It just simply only takes 3 elements rather than 6, and prints them back. What's going on?
My apologies if this is a well known issue. I'm not familiar with terms used in programming much, so it's not easy for me to search for questions.
All the answers and comments mentioned it right. I will just add one more thing. Earlier the \n were also taken as input by the scanf. As a result
your loop ended and still the characters you desired were not read.
why the solution scanf("%c ",..) works?
Now, the trailing one is telling scanf() to skip any trailing
whitespace after the character input. It therefore keeps reading input
until it sees something that is not whitespace or the end of the
stream.
Also as pointed out, the leading white space would also let you achieve the same thing with the added benefit of having a smooth interactive input.
To give you an idea of what I mean I would give an excample:
int n,m;
scanf("%d ",&n);
printf("n is %d\n",n);
printf("Give 2nd number\n");
scanf("%d ",&m);
printf("m is %d\n",m);
So now you start giving input.
1
Enter
Now you expect so see the output n is 1. But it seems like it stopped.
You again type 2Enter
Now you see the output: n is 1. Then you see the output
n is 1
6<enter>
Give 2nd number
m is 2
That's what I meant when asked to avoid the trailing whitespace.
When you type in:
a
b
s
The Enter keystroke is counted as its own character (the newline character, '\n'), so you end up storing the following in c: ['a', '\n', 'b', '\n', 's', '\n'].
If you want to consume the newline, you can include it in the scanf() call; something like this:
scanf("\n%c",&c[i]);
I'm trying to build a component similar to Google Play's credit card adding:
Where the user starts typing the credit card number, and only the credit card images that stay visible, are of the cards that matches part of the credit card number pattern.
For example:
Looking at MasterCard regex: ^5[1-5][0-9]{14}$
If the user type "5", "53", "531", the image of master card should be visible.
I guess it can be done with Pattern and Matcher class, but how?
Using match() method is not good, as it trying to match against all the pattern.
Thanks in advance!
If you want a pattern for live validation, you can use
^5([1-5][0-9]{0,14})?$
See the regex demo.
Note you cannot use it for final string validation, you will have to use your current regex for it.
The main thing about a regex for live input validation is that it allows the next character only if the previous one matches, and that is possible with nested optional groups. Since you have only 3 parts: 1) the first obligatory 5, then 1 to 5 digit, and then any 0 to 14 digits, you may use just one optional group around [1-5][0-9]{0,14} pattern and and make sure you allow zero or up to 14 other digits.
Details:
^ - start of string
5 - obligatory 5
([1-5][0-9]{0,14})? - an optional sequence (1 or 0 occurrences) of:
[1-5] - a digit from 1 to 5
[0-9]{0,14} - any zero to forteen digits
$ - end of string.
Use your pattern for activation the buttonand this for the image
^5[1-5][0-9]{0, 14}$
I am writing a dictionary-type app. I have a list of hash-mapped terms and definitions. The basic premise is that there is a list of words that you tap on to see the definitions.
I have this functionality up and running - I am now trying to put dynamic links between the definitions.
Example: say the user taps on an item in the list, "dog". The definition might pop up, saying "A small furry [animal], commonly kept as a pet. See also [cat].". The intention is that the user can click on the word [animal] or [cat] and go to the appropriate definition. I've already gone to the trouble of making sure that any links in definitions are bounded by square brackets, so it's just a case of scanning the pop-up string for text [surrounded by brackets] and providing a link to that definition.
Note that definitions can contain multiple links, whilst some don't contain any links.
I have access to the string before it is displayed, so I guess the best way to do this is to do the scanning and ready the links before the dialog box is displayed.
The question is, how would I go about scanning for text surrounded by square brackets, and returning the text contained within those brackets?
Ideally the actual dialog box that is displayed would be devoid of the square brackets, and I need to also figure out a way of putting hyperlinks into a dialog box's text, but I'll cross that bridge when I come to it.
I'm new to Java - I've come from MATLAB and am just about staying afloat, but this is a less common task than I've had to deal with so far!
You could probably do this with a regular expression; something like this:
([^[]*)(\[[^]]+\])
which describes two "match groups"; the first of which means any string of zero or more characters that aren't "[" and the second of which means any string starting with "[", containing one or more characters that aren't "]", and ending with "]".
Then you could scan through your input for matches to this pattern. The first match group is passed through unchanged, and the second match group gets converted to a link. When the pattern stops matching your input, take whatever's left over and transmit that unchanged as well.
You'll have to experiment a little; regular expressions typically take some debugging. If your link text can only contain alphanumerics and spaces, your pattern would look more like this:
([^[]*)(\[[\s\w]+\])
Also, you may find that regular expression matching under Android is too slow to be practical, in which case you'll have to use wasyl's suggestion.
Quite simple, I think... As the text is in brackets, you need to scan every letter. So the basic recipe would be :
in a while loop scan every character (let's say, while i < len(text))
If scanned character is [:
i++;
Add letter at index i to some temporary variable
while (character # i) != ']' append it to the temporary variable
store this temporary variable in a list of results.
Some tips:
If you use solution above, use StringBuilder to append text (as regular string is immutable)
You might also want (and it's better, I think) to store starting and ending positions of all square brackets first, and then use string.substring() on each pair to get the text inside. This way you'd first iterate definition to find brackets (maybe catch unmatched ones, for early error handling), then iterate pairs of indices...
As for links, maybe this will be of use: How can I get clickable hyperlinks in AlertDialog from a string resource?