简体   繁体   English

使用正则表达式Java匹配数字和字母/数字(分隔)

[英]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? 例如,当我输入“ SAL45”时,输出为“ It's a variable”,这很好,所以当我输入“ 45”时,输出再次为“ It's a variable”,但我需要输出为“ It's a number” ”,我该如何解决该错误?

With "45", both messages are printed. 使用“ 45”时,将同时打印两条消息。 You just need to make use of else to show only one message. 您只需要利用else仅显示一条消息即可。 Here's the corrected code:- 这是更正的代码:-

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

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

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] or $ 必须以_或字母[a-zA-Z]或$开头
  2. Other Character Should be _ , Number[0-9], Alphabet[a-zA-Z], $ 其他字符应为_ ,数字[0-9],字母[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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM