如何只使用java正则表达式匹配字母,匹配方法?
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]"); } }
输出为False。 我哪里错了? 此外,我想检查一个单词是否只包含字母,并且可能或可能不以一个句点结束。 这是什么样的正则表达式?
即“abc”“abc。” 有效但“abc ..”无效。
我可以使用indexOf()
方法来解决它,但我想知道是否可以使用单个正则表达式。
"[a-zA-Z]"
只匹配一个字符。 要匹配多个字符,请使用"[a-zA-Z]+"
。
由于点是任何角色的小丑,你必须掩盖它: "abc\."
要使点可选,您需要一个问号: "abc\.?"
如果在代码中将Pattern作为文字常量编写,则必须屏蔽反斜杠:
System.out.println ("abc".matches ("abc\\.?")); System.out.println ("abc.".matches ("abc\\.?")); System.out.println ("abc..".matches ("abc\\.?"));
结合两种模式:
System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));
而不是a-zA-Z,\ w通常更合适,因为它捕获äöüßø等外来字符:
System.out.println ("abc.".matches ("\\w+\\.?"));
[A-Za-z ]*
匹配字母和空格。
matches
方法执行整行的匹配,即它等同于find()
和’^ abc $’。 所以,只需使用Pattern.compile("[a-zA-Z]").matcher(str).find()
代替。 然后修复你的正则表达式。 正如@user未知提到的,你的正则表达式实际上只匹配一个字符。 你应该说[a-zA-Z]+
这里有三个问题:
- 只需使用
String.matches()
– 如果API在那里,请使用它 - 在java中,“匹配”意味着“匹配整个输入”,恕我直言,这是违反直觉的,所以让你的方法的API通过让调用者考虑匹配输入的一部分来反映这一点,如你的例子所示
- 你的正则表达式只匹配1个字符
我建议你使用这样的代码:
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 }