[英]How to match letters only using java regex, matches method?
import java.util.regex.Pattern;
class HowEasy {
public boolean matches(String regex) {
System.out.println(Pattern.matches(regex, "abcABC "));
return Pattern.matches(regex, "abcABC");
}
public static void main(String[] args) {
HowEasy words = new HowEasy();
words.matches("[a-zA-Z]");
}
}
The output is False. 输出为False。 Where am I going wrong?
我哪里错了? Also I want to check if a word contains only letters and may or maynot end with a single period.
此外,我想检查一个单词是否只包含字母,并且可能或可能不以一个句点结束。 What is the regex for that?
这是什么样的正则表达式?
ie "abc" "abc." 即“abc”“abc。” is valid but "abc.." is not valid.
有效但“abc ..”无效。
I can use indexOf()
method to solve it, but I want to know if it is possible to use a single regex. 我可以使用
indexOf()
方法来解决它,但我想知道是否可以使用单个正则表达式。
"[a-zA-Z]"
matches only one character. "[a-zA-Z]"
只匹配一个字符。 To match multiple characters, use "[a-zA-Z]+"
. 要匹配多个字符,请使用
"[a-zA-Z]+"
。
Since a dot is a joker for any character, you have to mask it: "abc\\."
由于点是任何角色的小丑,你必须掩盖它:
"abc\\."
To make the dot optional, you need a question mark: "abc\\.?"
要使点可选,您需要一个问号:
"abc\\.?"
If you write the Pattern as literal constant in your code, you have to mask the backslash: 如果在代码中将Pattern写为文字常量,则必须屏蔽反斜杠:
System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));
Combining both patterns: 结合两种模式:
System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));
Instead of a-zA-Z, \\w is often more appropriate, since it captures foreign characters like äöüßø and so on: 而不是a-zA-Z,\\ w通常更合适,因为它捕获äöüßø等外来字符:
System.out.println ("abc.".matches ("\\w+\\.?"));
[A-Za-z ]*
匹配字母和空格。
matches
method performs matching of full line, ie it is equivalent to find()
with '^abc$'. matches
方法执行匹配的整行,即它等同于find()
和'^ abc $'。 So, just use Pattern.compile("[a-zA-Z]").matcher(str).find()
instead. 所以,只需使用
Pattern.compile("[a-zA-Z]").matcher(str).find()
代替。 Then fix your regex. 然后修复你的正则表达式。 As @user unknown mentioned your regex actually matches only one character.
正如@user未知提到的,你的正则表达式实际上只匹配一个字符。 You probably should say
[a-zA-Z]+
你应该说
[a-zA-Z]+
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.*;
/* Write an application that prompts the user for a String that contains at least
* five letters and at least five digits. Continuously re-prompt the user until a
* valid String is entered. Display a message indicating whether the user was
* successful or did not enter enough digits, letters, or both.
*/
public class FiveLettersAndDigits {
private static String readIn() { // read input from stdin
StringBuilder sb = new StringBuilder();
int c = 0;
try { // do not use try-with-resources. We don't want to close the stdin stream
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((c = reader.read()) != 0) { // read all characters until null
// We don't want new lines, although we must consume them.
if (c != 13 && c != 10) {
sb.append((char) c);
} else {
break; // break on new line (or else the loop won't terminate)
}
}
// reader.readLine(); // get the trailing new line
} catch (IOException ex) {
System.err.println("Failed to read user input!");
ex.printStackTrace(System.err);
}
return sb.toString().trim();
}
/**
* Check the given input against a pattern
*
* @return the number of matches
*/
private static int getitemCount(String input, String pattern) {
int count = 0;
try {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
while (m.find()) { // count the number of times the pattern matches
count++;
}
} catch (PatternSyntaxException ex) {
System.err.println("Failed to test input String \"" + input + "\" for matches to pattern \"" + pattern + "\"!");
ex.printStackTrace(System.err);
}
return count;
}
private static String reprompt() {
System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: ");
String in = readIn();
return in;
}
public static void main(String[] args) {
int letters = 0, digits = 0;
String in = null;
System.out.print("Please enter five letters and five digits in any order: ");
in = readIn();
while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input
if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both
// count the letters and numbers. If there are enough, this loop won't happen again.
letters = getitemCount(in, "[A-Za-z]");
digits = getitemCount(in, "[0-9]");
if (letters < 5 || digits < 5) {
in = reprompt(); // reset in case we need to go around again.
}
} else {
in = reprompt();
}
}
}
}
Three problems here: 这里有三个问题:
String.matches()
- if the API is there, use it String.matches()
- 如果API在那里,请使用它 I recommend you use code like this: 我建议你使用这样的代码:
public boolean matches(String regex) {
regex = "^.*" + regex + ".*$"; // pad with regex to allow partial matching
System.out.println("abcABC ".matches(regex));
return "abcABC ".matches(regex);
}
public static void main(String[] args) {
HowEasy words = new HowEasy();
words.matches("[a-zA-Z]+"); // added "+" (ie 1-to-n of) to character class
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.