0

我无法使用正则表达式来显示何时需要在正确的显示器中显示。现在我有了这个代码,这是一个简单易用的正则表达式,但我仍然不明白它是如何工作的。有没有办法过滤字符串以仅显示大写字母?

假设我输入了一个很长的名字句子:

泰勒肖恩卡西乔恩彼得。

如果我不知道字符串中可能包含哪些名称,我如何才能让字符串只显示一个名称?(说是随机名字,每次都会填)

import java.io.Console;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter your Regex: ");
        Pattern pattern = 
        Pattern.compile(input.nextLine());


        System.out.println("Enter String to Search");
        Matcher matcher =
        pattern.matcher(input.nextLine());

        boolean found = false;
        while (matcher.find()) {
            System.out.println("I found the text" + " " + matcher.group() +" starting at " + "index " + matcher.start() + " and ending at index " + matcher.end());
            found = true;
        }

        if (!found) {
            System.out.println("No match found.");
        }
    }

}
4

1 回答 1

1

您可以在字符集中使用范围

[A-Z][a-z]*

这意味着一个大写字母,后跟零个或多个小写字母

看到它在行动


如果您对仅 ASCII 字母不满意,可以使用:

\\p{Upper}\\p{Lower}*
于 2015-12-09T19:50:50.450 回答