Baker1562 Baker1562 - 2 months ago 6
Java Question

Match numbers and letters/numbers using regex java (by separated)

what it's the correct form to match when an String is number o letters/number, for example, I have this code

String regexNum = "\\d*";
String regexVar = "[a-zA-Z0-9]*";

if(valor.matches(regexNum))
{
System.out.println("It's a number");
}
if(valor.matches(regexVar))
{
System.out.println("It's a variable");
}


When I enter for example "SAL45", the output is "It's a variable", what's fine, so, when a I enter "45", the output is "It's a variable" again but I need to output be "It's a number", how can I fix that mistake?

Answer

Your regex is not correct.

Here is the Condition for Number :

  1. Length Must greater than zero
  2. All there character should be digits

And Here is the Condition for a Variable :

  1. Must Start with _ or Alphabet [a-zA-Z]
  2. Other Character Should be _, Number[0-9], Alphabet[a-zA-Z]

    String regexNum = "\\d+";
    String regexVar = "[a-zA-Z_][a-zA-Z_0-9]*";

    if (valor.matches(regexNum)) {
        System.out.println("It's a number");
    }
    if (valor.matches(regexVar)) {
        System.out.println("It's a variable");
    }

Comments