英文:
Is this an appropriate use of regex and string.matches?
问题
boolean isValid(String candidate)
{
if(candidate.matches("[^\\d|\\s]+"))
{
return false;
}
return true;
}
英文:
I'm trying to check if a string being passed in like "055# 444$ 285" contains any non-whitespace or digits and decided regex might be useful here (never used it before). If the string contains any non-whitespace or non-digits I want to return false.
Using regex and string.matches can I do what I want or is there another method I should use?
boolean isValid(String candidate)
{
if(candidate.matches("[^\\d|\\s]+"))
{
return false;
}
return true;
}
答案1
得分: 1
问题
您当前的代码检查整个字符串是否与从开头到结尾的非数字/非空白/非竖线 (|
) 字符匹配。改为改为从开头到结尾匹配 [\d\s]
并返回结果。在字符集中不需要使用竖线进行交替(它将精确匹配该字符)。
您可以通过将以下字符串传递给当前的程序来测试其运行情况:
!@# # 返回true
||| # 返回false
1 2 # 返回false
修复
您可以改为使用以下内容。它检查整个字符串是否仅与数字和空白字符匹配:
return candidate.matches("[\\d\\s]+");
class Main {
public static void main(String[] args) {
boolean valid = isValid("055 444 285");
System.out.printf(Boolean.toString(valid));
}
static boolean isValid(String candidate) {
return candidate.matches("[\\d\\s]+");
}
}
英文:
Problem
Your current code checks to see if the entire string matches non-digit/non-whitespace/non-pipe (|
) characters from start to finish. Change it instead to match [\d\s]
from start to finish and return the result. The pipe is not needed in character sets for alternation (it'll match that character literally).
You can test how your current program is running by passing it the following strings:
!@# # returns true
||| # returns false
1 2 # returns false
Fix
You can use the following instead. It checks that the entire string matches only digits and whitespace characters:
return candidate.matches("[\\d\\s]+");
class Main {
public static void main(String[] args) {
boolean valid = isValid("055 444 285");
System.out.printf(Boolean.toString(valid));
}
static boolean isValid(String candidate) {
return candidate.matches("[\\d\\s]+");
}
}
答案2
得分: 0
匹配适用于整个字符串。
你的意思是:
整个字符串是否符合以下描述:
- 第一个字符不是数字,不是连字符,也不是空白字符。
- 然后我们要么已经到达末尾,要么是另一个非数字、非连字符、非空白字符。
- 一直继续,直到结尾。
显然,“055# 444$ 285”确实不符合该正则表达式。从第一个字符开始:0 是数字。
你想要的是:在任何地方只有一个非数字、非空格字符吗?那么 - 无效。所以,你想要使用 find
,而不是 matches
,并且不需要加号。很可能,你也不需要 |
。
英文:
matches goes for the ENTIRE string.
You're saying:
Does the ENTIRE string fit this description:
- The first character is not a digit, not a bar, and not a whitespace.
- Then we're either at the end, or another non-digit, non-bar, non-whitespace char.
- Keep going until the end.
Obviously, "055# 444$ 285" is indeed NOT matching that regexp. Starts right at the first character: 0 is a digit.
What you want is: Is there just a single non-digit, non-space character anywhere in it? Then - invalid. So, you want find
, not matches
, and you don't want the plus. Presumably, you don't want the | either.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论