Reputation: 35
Does the following code ensure that the 'myteststring' contains only two digit numbers?If not, how to modify it?
if(myteststring.matches("^[0-9]*\\$"))
{
// Do something
}
else {
// Do something else
}
Upvotes: 0
Views: 74
Reputation: 325
To match a string that contains at least one pair of digits, any combination of characters, and with the restriction that numbers are exactly two digits:
myteststring.matches("^[^0-9]*([0-9]{2}[^0-9]+)*[0-9]{2}[^0-9]*$")
To include the empty string:
myteststring.matches("^[^0-9]*([0-9]{2}[^0-9]+)*([0-9]{2})?[^0-9]*$")
To match a sting that contains exactly two digits:
myteststring.matches("^[0-9]{2}$")
Or
myteststring.matches("^[0-9][0-9]$")
The ^
means match the beginning of the line. When used inside of the square brackets, it matches the opposite of the pattern.
The [0-9]
means match one of the. numbers from 0 through 9.
The {2}
means match the previous regex twice.
The $
means match the end of line.
Upvotes: 2
Reputation: 36304
use (\\d{2})+
. This checks for pairs of digits.
demo here
Output :
myString ="123" -- > false
myString ="12" -- > true
myString ="1234" --> true
Upvotes: 2