Java 用于检查字符串中第一个字母的正则表达式

Java 用于检查字符串中第一个字母的正则表达式,java,regex,Java,Regex,一个正则表达式,用于检查从给定输入字符串构造APPLE的单词。这方面的一个例子是“Ap人们看到personl为e每个人而努力。 到目前为止,这就是我所做的 // Pattern applePattern = Pattern.compile("\\w+^[aA]?"); // Matcher outputApple; // String apple; // do { // System.out.print("Enter

一个正则表达式,用于检查从给定输入字符串构造APPLE的单词。这方面的一个例子是“Ap人们看到personle每个人而努力。 到目前为止,这就是我所做的

//        Pattern applePattern = Pattern.compile("\\w+^[aA]?");
//        Matcher outputApple;
//        String apple;
//        do {
//            System.out.print("Enter a string that contructs the word APPLE: ");
//            apple = input.nextLine();
//            outputApple = applePattern.matcher(apple);
//        } while (!outputApple.find());

    String applePattern=("\\w+^[aA]?");
    String outputApple;
    String apple;
    do{
        System.out.println("Enter a string that contructs the word APPLE: ");
        apple=input.nextLine();
        outputApple=apple.matches(applePattern)?"TRUE":"FALSE";
    }while(outputApple.equals("FALSE"));
另外,你推荐什么?注释代码还是其他

编辑:它现在正常工作了

 String applePattern = ("[Aa].*? p.*? p.*? l.*? e\\S*");
    String outputApple;
    String apple;
    do {
        System.out.print("Enter a string that contructs the word APPLE: ");
        apple = input.nextLine();
        outputApple = apple.matches(applePattern) ? "TRUE" : "FALSE";
    } while (outputApple.equals("FALSE"));

看起来你是指这个图案

[Aa].*? p.*? p.*? l.*? e\\S*
代码:

说明:

  • [Aa]
    匹配大写
    a
    或小写
    a
  • *?
    匹配空格内的任何字符
  • p
    空格后面的字符将是一个字母
    p
    。同样,它也会出现在
    e
  • \S*
    匹配零个或多个非空格字符

    • [Aa]\w+\s+p\w+\s+p\w+\s+l\w+\s+e
      @MarounMaroun:好的,但问题是
      请参见和
      查看OP的输入中的
      第二个代码是什么让你产生的?我会避免字符串比较…这就是布尔值的含义是的。这是有效的,我会添加解释以使它得到更好的答案。它匹配
      坏的ple
      ,你还需要
      \b
      [Aa]
      之前,它是一个matches方法。它尝试匹配整个字符串。我只是在谈论regex,而不是它的使用方式。但是+1是一个很好的答案
      String s = "A people see person leaving for everyone";
      System.out.println(s.matches("[Aa].*? p.*? p.*? l.*? e\\S*")); // true