ALV
ALV

Reputation: 569

how to check string contain any character other than number in java?

I want to check String contain any character or special character other than number.I wrote following code for this

String expression = "[^a-zA-z]";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(jTextFieldPurchaseOrder.getText().toString().trim());

It is working fine when i am taking value from jTextField and checking my condition. But giving error when checking String from DTO as below

list.get(0).getChalan_trans_id().toString().trim().matches("[^a-zA-z]");

Where list is arraylist of DTO. I am not getting where am I going wrong?

Thanks

Upvotes: 0

Views: 1236

Answers (2)

AustinDahl
AustinDahl

Reputation: 852

There's probably a more efficient way than regular expressions. Regular expressions are powerful, but can be overkill for a simple task like this.

Something like this ought to work, and I would expect it to be quicker.

static boolean hasNonNumber(String s) {
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (!Character.isDigit(c)) {
            return true;
        }
    }
    return false;
}

Upvotes: 0

Keppil
Keppil

Reputation: 46239

If you want to check if there is a non-digit character, you can use .*\\D.*:

if (list.get(0).getChalan_trans_id().toString().trim().matches(".*\\D.*")) {
    //non-digit found, handle it
}

or, maybe easier, do it the other way around:

if (list.get(0).getChalan_trans_id().toString().trim().matches("\\d*")) {
    //only digits found
}

Upvotes: 4

Related Questions