检查输入是否以数字开头并以大写字母结尾

Checking if the input starts with a number and ends with an Upper letter

我不知道为什么这不起作用,因为即使我键入以数字开头、包含 "end" 并以大写字母结尾的句子,它们的值仍然为 0 .另外,这应该区分大小写。

if (sentence.startsWith("[0-9]") && sentence.contains("end") && (sentence.endsWith("[A-Z]"))) {
    y++;
}
System.out.println(y);

查看此 REGEX (^[0-9]+)(end)([A-Z]+$) 以一位或多位数字开头并以一位或多位大写字符结尾

    if (sentence.matches("(^[0-9]+)(end)([A-Z]+$)")) {
        y++;
    }
    System.out.println(y);

您的代码无效,因为 String::startWith doesn't take a regex as a parameter while you are using a regex. You need to use String::matches 如下所示:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int no = 0;
        while (no < 4) {
            System.out.print("Type a number >4: ");
            no = Integer.parseInt(scan.nextLine());
        }
        String sentence;
        int y = 0;
        for (int i = 0; i < no; i++) {
            System.out.print("Enter a sentence: ");
            sentence = scan.nextLine();
            if (sentence.matches("[0-9]+.*end.*[\p{javaUpperCase}]")) {
                y++;
            }
        }
        System.out.println(y);
    }
}

样本运行:

Type a number >4: 5
Enter a sentence: Hello world
Enter a sentence: 123 Hello World ends with LD
Enter a sentence: 123HelloendHH
Enter a sentence: Good morning
Enter a sentence: 123Good morning
2

试试这个。由于它们的开销,我尽量避免使用 regular expressions 除非它真的简化了任务。在这种情况下,有一些方法可以促进该过程。

另外,句首和句尾的白色space会影响结果(即不修剪)


int lastIdx = sentence.length()-1;
if (Character.isDigit(sentence.charAt(0))
        && sentence.contains("end")  
        && Character.isUpperCase(sentence.charAt(lastIdx))) {
           y++;
}