Check If String Contains Only Numbers or Only Characters (R)

Check if string contains ONLY NUMBERS or ONLY CHARACTERS (R)

you need to persist your regex

all_num <- "123"
all_letters <- "abc"
mixed <- "123abc"

grepl("^[A-Za-z]+$", all_num, perl = T) #will be false
grepl("^[A-Za-z]+$", all_letters, perl = T) #will be true
grepl("^[A-Za-z]+$", mixed, perl=T) #will be false

Check if string contains anything but numbers

We can use the pattern to match only one or more non-numeric elements ([^0-9]+) from start (^) to the end ($) of the string with grepl.

grepl('^[^0-9]+$', teststring)

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).

Test if String contains Letters and Characters

Assuming the numbers and letters will be in any order you can do :

grepl('([a-zA-Z]+[0-9]+)|([0-9]+[a-zA-Z]+):', bar)
#[1] FALSE FALSE TRUE TRUE

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.

Check if a string contains a number

You can use any function, with the str.isdigit function, like this

def has_numbers(inputString):
return any(char.isdigit() for char in inputString)

has_numbers("I own 1 dog")
# True
has_numbers("I own no dog")
# False

Alternatively you can use a Regular Expression, like this

import re
def has_numbers(inputString):
return bool(re.search(r'\d', inputString))

has_numbers("I own 1 dog")
# True
has_numbers("I own no dog")
# False


Related Topics



Leave a reply



Submit