I am trying to figure out how to make sure a String variable does not have a number as a string. I cannot Import anything.
I have tried
NameArray[i].equalsIgnoreCase("")) || Integer.parseInt(NameArray[i]) >= 48 && Integer.parseInt(NameArray[i]) < 58
but it did not work.
You can try converting string to number using Integer.parseInt(string). If it gives an Exception than it is not a number.
public boolean validNumber(String number)
{
try
{
Integer.parseInt(number);
}
catch (NumberFormatException e)
{
return false;
}
return true;
}
In Java 8+, you might use an IntStream
to generate a range ( [48, 58]
) and then check if that as a String
is equal to your NameArray
. Something like,
if (IntStream.rangeClosed(48, 58).anyMatch(x -> String.valueOf(x)
.equals(NameArray[i]))) {
}
You mention that you want to make sure it doesn't contain a value - so perhaps you really want noneMatch
like
if (IntStream.rangeClosed(48, 58).noneMatch(x -> String.valueOf(x)
.equals(NameArray[i]))) {
}
So, you need to check for a string which doesn't contain any numbers. Try using regex .*[0-9].*
which will check for occurrence of any numerical character in your string.
String regex = ".*[0-9].*";
// Returns true
System.out.println("1".matches(regex));
System.out.println("100".matches(regex));
System.out.println("Stack 12 Overflow".matches(regex));
System.out.println("aa123bb".matches(regex));
// Returns false
System.out.println("Regex".matches(regex));
System.out.println("Java".matches(regex));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.