Java String - See if a string contains only numbers and not letters
If you'll be processing the number as text, then change:
if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
to:
if (text.matches("[0-9]+") && text.length() > 2) {
Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.
If you actually want to use the numeric value, use Integer.parseInt()
or Double.parseDouble()
as others have explained below.
As a side note, it's generally considered bad practice to compare boolean values to true
or false
. Just use if (condition)
or if (!condition)
.
How do you check in python whether a string contains only numbers?
You'll want to use the isdigit
method on your str
object:
if len(isbn) == 10 and isbn.isdigit():
From the isdigit
documentation:
str.isdigit()
Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
How to check if a string contains only digits in Java
Try
String regex = "[0-9]+";
or
String regex = "\\d+";
As per Java regular expressions, the +
means "one or more times" and \d
means "a digit".
Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d
in a java String gives you the actual result: \d
References:
Java Regular Expressions
Java Character Escape Sequences
Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.
Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
Question 1:
Isn't it necessary to add
^
and$
to the regex, so it won't match "aa123bb" ?
No. In java, the matches
method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$
(even though it is also correct). Please see the last negative test case.
Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find
method instead, described in detail here:
Difference between matches() and find() in Java Regex
Question 2:
Won't this regex also match the empty string,
""
?*
No. A regex \\d*
would match the empty string, but \\d+
does not. The star *
means zero or more, whereas the plus +
means one or more. Please see the first negative test case.
Question 3
Isn't it faster to compile a regex Pattern?
Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches
, and so if performance implications are important then a Pattern
can be compiled and used like this:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
Check if string contains only digits
how about
let isnum = /^\d+$/.test(val);
How to I check that a string contains only digits and / in python?
There are many options, as showed here. A nice one would be list comprehensions.
Let's consider two strings, one that satisfies the criteria, other that doesn't:
>>> match = "123/456/"
>>> no_match = "123a456/"
We can check if a character of them matches by using isdigit()
and comparation:
>>> match[0].isdigit() or match[0] == '/'
True
But we want to know if all chars match. We can get a list of results by using list comprehensions:
>>> [c.isdigit() or c == '/' for c in match]
[True, True, True, True, True, True, True, True]
>>> [c.isdigit() or c == '/' for c in no_match]
[True, True, True, False, True, True, True, True]
Note that the list of the non-matching string has False
at the same position of the 'a'
char.
Since we want all chars to match, we can use the all()
function. It expects a list of values; if at least one of them is false, then it returns false:
>>> all([c.isdigit() or c == '/' for c in match])
True
>>> all([c.isdigit() or c == '/' for c in no_match])
False
Bonus points
Put on a function
You would be better to put it on a function:
>>> def digit_or_slash(s):
... return all([c.isdigit() or c == '/' for c in s])
...
>>> digit_or_slash(match)
True
>>> digit_or_slash(no_match)
False
Generator expressions
Generator expressions tend to be more efficient:
>>> def digit_or_slash(s):
... return all(c.isdigit() or c == '/' for c in s)
...
But in your case it is probably negligible anyway.
What about in
?
I would prefer to use the in
operator, as below:
>>> def digit_or_slash(s):
... return all(c in "0123456789/" for c in s)
Note that this is only one of the options. Sadly, your problem fails this Zen of Python recommendation (>>> import this
):
There should be one- and preferably only one -obvious way to do it.
But that's ok, now you can choose whatever you prefer :)
Fastest way to check if string contains only digits in C#
bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
Will probably be the fastest way to do it.
Check if a string contains only digits and white space in java Android
As @ADM suggested in comment you can update your regex [0-9]+
with below
[0-9 ]+
so it look like
String Cardresult = edtCashCard.getText().toString();
if (Cardresult.matches("[0-9 ]+")){
Toast.makeText(getApplicationContext(), "Good Job the strings are numbers", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error the string contains character", Toast.LENGTH_SHORT).show();
}
how to check if the string contains only numbers or word in c
*str
this is a pointer to the first character of the string so along your cycle it only checks this first character.
Furthermore you are returning values before checking the entire string, you need to use flags and set them along the cycle for digits caps and small letters, and in the end return the values according to those flags.
There is the <ctype.h>
library which has functions like isalpha
and isdigit
and can make your job easier, for that I refer you to @DevSolar answer as a better method.
If you can't use it this is the way to go:
Live demo
int categorize(char *str) {
int x = 0;
int is_digit, is_cap, is_small;
is_cap = is_digit = is_small = 0;
while (str[x] != '\0') {
if (!(str[x] >= 'a' && str[x] <= 'z') && !(str[x] >= 'A' && str[x] <= 'Z') && !(str[x] >= '0' && str[x] <= '9'))
return 6;
if (str[x] >= 'A' && str[x] <= 'Z' && !is_cap) //if there are caps
is_cap = 1;
if (str[x] >= '0' && str[x] <= '9' && !is_digit) //if there are digits
is_digit = 1;
if (str[x] >= 'a' && str[x] <= 'z' && !is_small) //if there are smalls
is_small = 1;
x++;
}
if ((is_small || is_cap) && is_digit){
return 5;
}
if(is_small && is_cap){
return 3;
}
if(is_digit){
return 4;
}
if(is_small){
return 2;
}
if(is_cap){
return 1;
}
return 6;
}
Note that this kind of character arithmetic works well in ASCII but fails in other character encodings like EBCDIC which don't have sequencial order for alphabetic characters.
How to check if a string only contains digits/numerical characters
Here it is:
#!/bin/bash
if [[ $1 =~ ^[0-9]+$ ]]
then
echo "ok"
else
echo "no"
fi
It prints ok
if the first argument contains only digits and no
otherwise. You could call it with: ./yourFileName.sh inputValue
Related Topics
Pass Data or Modify Extension HTML in a New Tab/Window
Differencebetween State and Props in React
How to Post Form Data with Fetch API
Remove All White Spaces from Text
How to Set Multiple CSS Styles in JavaScript
Getting Unexpected Token Export
How to Capitalize First Letter of Each Word, Like a 2-Word City
Get Protocol, Domain, and Port from Url
Pass Parameters in Setinterval Function
JavaScript Get Window X/Y Position for Scroll
Difference Between "Change" and "Input" Event for an 'Input' Element
How to Insert Text into the Textarea at the Current Cursor Position
Angularjs - How to Use $Routeparams in Generating the Templateurl
How to Prevent Caching of My JavaScript File
Object Method with Es6/Bluebird Promises
Casting Plain Objects to Class Instances in JavaScript
What Do Curly Braces Inside of Function Parameter Lists Do in Es6