[英]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 : 这是数字的条件:
And Here is the Condition for a Variable : 这是变量的条件:
_
or Alphabet [a-zA-Z] or $
_
或字母[a-zA-Z]或$
开头 _
, 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.