【问题标题】:How to match letters only using java regex, matches method?如何仅使用 java 正则表达式匹配字母,匹配方法?
【发布时间】:2023-03-06 11:50:01
【问题描述】:
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]");
    }
}

输出为假。我哪里错了?另外我想检查一个单词是否只包含字母,并且可能会或可能不会以单个句点结尾。那是什么正则表达式?

即“abc”“abc”。有效,但“abc..”无效。

我可以使用indexOf() 方法来解决它,但我想知道是否可以使用单个正则表达式。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    "[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]+\\.?"));
    

    \w 通常比 a-zA-Z 更合适,因为它捕获了像 äöüßø 等外来字符:

    System.out.println ("abc.".matches ("\\w+\\.?"));   
    

    【讨论】:

    • 你是对的 [a-zA-Z]+ 现在它只匹配字母。实际上第二个表达式应该是“abc\\.?” (在日食中)
    • in eclipse 不是重点。您可以从文件、命令行、JTextField 输入模式,而不是源代码中的文字常量 - 这会有所不同。我在编辑时提到了它 (mask the backslash)。无论如何,谢谢。
    • 请注意,\w 还捕获下划线和数字,即 [a-zA-Z_0-9],如 Pattern 中定义的那样
    【解决方案2】:

    [A-Za-z ]* 匹配字母和空格。

    【讨论】:

      【解决方案3】:

      matches 方法执行整行匹配,即相当于 find() 与 '^abc$'。因此,只需使用 Pattern.compile("[a-zA-Z]").matcher(str).find() 代替。然后修复你的正则表达式。正如@user unknown 提到的,您的正则表达式实际上只匹配一个字符。你可能应该说[a-zA-Z]+

      【讨论】:

        【解决方案4】:

        这里有三个问题:

        1. 只需使用String.matches() - 如果有 API,请使用它
        2. 在 java 中,“matches”的意思是“匹配整个输入”,恕我直言,这是违反直觉的,所以让您的方法的 API 反映这一点,让调用者考虑匹配 part 你的例子所暗示的输入
        3. 您的正则表达式仅匹配 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
        }
        

        【讨论】:

          【解决方案5】:
          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();
                }
              }
            }
          
          }
          

          【讨论】:

            猜你喜欢
            • 2011-04-06
            • 2011-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-29
            • 1970-01-01
            相关资源
            最近更新 更多