This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
What your code checks is whether the string matches the pattern "exactly one digit". That's obviously not what you want.
One way to reword "contains a number" is "matches an arbitrary number of arbitrary characters, followed by a digit, followed by an arbitrary number of arbitrary characters.
Does that give you an idea on how to translate that in a regular expression?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Oct 05, 2007
I need that if user gives a word it should contain atleast one number in any position, the string must contain atleaset one number.
String.matches() doesn't look for a substring to match the pattern, but checks whether the whole string matches the pattern. You will see that "6".matches("\\d") returns true but "x6".matches("\\d") returns false.
You need to create a Pattern object and use the find() function. Take a look at the documentation, it is pretty clear. [ October 29, 2007: Message edited by: Jan van Mansum ]
I wouldn't use a Pattern object as Jan suggested. You are on the right track, but as Ilja said, your pattern is not good enough. Currently you have "\\d" which translates to "string is exactly one digit", which is obvious not what you want. You want "string contains a number", which is the same as "string contains any number of characters, followed by a digit, followed by any number of characters", which would result in a slightly more complex pattern "xxx\\dxxx" where xxx translates into "any number of characters". Take a look at the mentionned documentation to see how to replace the xxx part.
I think you first need to decide what you are looking for. First you were looking for a single digit, now you are trying to find one of: lowercase letter, uppercase letter, digit.
Maybe it is not some much the Java as it is the regular expressions that are difficult or unfamiliar to you. There is plenty of resources about that on the internet, just type "regular expression tutorial" in Google.
it is printing as valid. special characters are not there in regular expression.
Well, neither are spaces in your regex... yet, it prints it as valid.
The reason is because you are using the find() method, which doesn't match the whole string, it only finds the substrings that matches.
BTW, at this point, you can either stay with your code that uses find() or go back to the code that uses matches(). If you choose the former, you need to have a regex that forces the whole string to be searched.
Henry [ October 29, 2007: Message edited by: Henry Wong ]