[英]Check if a string consists only of letters and / or hyphens with matches?
Good evening from Cologne. 从科隆晚安。
In a programming task I have to check if the given string consists only of letters and / or hyphens . 在编程任务中,我必须检查给定的字符串是否仅包含字母和/或连字符 。 Now I have an approach with matches .
现在我有一个搭配火柴的方法。 In the test of the word: "test-test-test" my code gives me false.
在测试单词“ test-test-test”中,我的代码给了我错误。 It should be true.
应该是真的 Do you know where the problem lies with me?
您知道问题出在哪里吗? Did I misunderstand at matches?
我在比赛中误会了吗? I thank you in advance.
我提前谢谢你。 Beautiful evening!
美丽的黄昏!
public class Zeichenketten {
public static boolean istName(String a) {
if (a.matches("[a-zA-Z]+") || a.matches("[-]+")) {
return true;
}
else {
return false;
}
}
}
Currently you're checking whether it's all letters, or all hyphens. 目前,您正在检查是全部字母还是所有连字符。 You just need to check whether it matches letters or hyphens :
您只需要检查它是否匹配字母或连字符 :
public static boolean istName(String a) {
return a.matches("[a-zA-Z-]+");
}
The -
at the end means "a hyphen" rather than "part of a range". 末尾的
-
表示“连字符”,而不是“范围的一部分”。
Note the simplification away from if/else - any time you write if (condition) return true; else return false;
请注意,简化是远离if / else的-在任何时候编写
if (condition) return true; else return false;
if (condition) return true; else return false;
you should just write return condition;
您应该只写
return condition;
for simplicity. 为简单起见。
Your code doesn't match your test string because String.matches() method returns true only when whole string matches by regex pattern. 您的代码与您的测试字符串不匹配,因为String.matches()方法仅在整个字符串均通过正则表达式模式匹配时才返回true。 In first case:
[a-zA-Z]+
you don't match because you have -
symbol in the string, in second where pattern is [-]+
you don't match because you have letters in string. 在第一种情况下:
[a-zA-Z]+
您不匹配,因为在字符串中有-
符号;在第二种情况下,模式为[-]+
您不匹配,因为在字符串中有字母。
You use wrong condition. 您使用了错误的条件。 You must create one regular expression and create good patern.
您必须创建一个正则表达式并创建良好的模式。
I recomended this page: https://regex101.com/ for test online regular expression. 我推荐此页面: https : //regex101.com/以测试在线正则表达式。
Try this for you example: 尝试以下示例:
public static boolean istName(String a) {
if (a.matches("[a-zA-Z-]+")) {
return true;
} else {
return false;
}
}
the hyphen has the ASCII value of 45, and you know that a string is an array of characters. 连字符的ASCII值为45,并且您知道字符串是字符数组。 So you have a loop to check each character of the given string, if it finds one with the ASCI 45, return true, else return false.
因此,您有一个循环来检查给定字符串的每个字符,如果找到带有ASCI 45的字符串,则返回true,否则返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.