[英]How to check a string which only contains one word. If a string has a sentence it should return false
I know it's a wierd to ask a question like this. 我知道提出这样的问题很奇怪。 But i've got no options. 但我没有选择。 The problem is 问题是
I've come across a requirement where i happens to add a condition where, If there is an input as a string, I should be able to allow all the strings which only contains one word. 我遇到了一个要求,我碰巧添加了一个条件,如果有一个输入作为字符串,我应该能够允许所有只包含一个单词的字符串。 So if there are many words I should reject. 所以如果有很多话,我应该拒绝。 How to add such check when I don't have specificity on such string. 当我对这样的字符串没有特异性时,如何添加这样的检查。
If the words are separated by some kind of white space, you could use a simple regular expression for this: 如果单词由某种空格分隔,则可以使用简单的正则表达式:
Pattern wordPattern = Pattern.compile("\\w+");
Matcher wordMatcher = wordPattern.matcher(inputString);
if (!wordMatcher.matches()) {
// discard user input
}
This will match all word characters ( [a-zA-Z_0-9]
). 这将匹配所有单词字符( [a-zA-Z_0-9]
)。 If your definition of "word" is different, the regex will need to be adapted. 如果您对“单词”的定义不同,则需要调整正则表达式。
So many ways you can achieve it, One of the simplest is.. 有很多方法可以实现它,其中最简单的是......
String str = "abc def";
String [] array = str.trim().split(" ");
if(array.lenght==1){
// allow if lenght = 1, or a word....
}else{
// don't allow if lenght !=1 , or not a word..., dosomething else, or skip
}
You can split the string on a regular expression that represents a sequence of white spaces and then see how many parts you get. 您可以将字符串拆分为表示一系列空格的正则表达式,然后查看您获得的部分数量。 Here's a function to do it: 这是一个功能:
public static boolean is_word(String s) {
return (s.length() > 0 && s.split("\\s+").length == 1);
}
System.out.println(is_word("word"));
System.out.println(is_word("two words"));
System.out.println(is_word("word\tabc\txyz"));
System.out.println(is_word(""));
Output : 输出 :
true false false false
The length check on the input string is required if you want to say that an empty string is not a word, which would seem reasonable. 如果你想说一个空字符串不是一个单词,那么输入字符串的长度检查是必需的,这似乎是合理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.