我在使用正则表达式来显示何时需要它在正确的显示中执行时遇到问题。 现在我有了这段代码,它是一个简单易用的正则表达式,但我仍然不明白它是如何工作的。有没有办法过滤字符串以仅显示大写字母?
假设我输入了一长串名字:
Tyler Sean Cassie Jon Peter.
如果我不知道字符串中可能包含哪些名称,如何才能使字符串仅显示一个名称? (说是随机名字,每次都会填)
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.");
}
}
}
最佳答案
您可以使用ranges inside character sets :
[A-Z][a-z]*
这意味着一个大写字母,后跟零个或多个小写字母。
<小时/>如果您不满足于仅使用 ASCII 字母,您可以使用:
\\p{Upper}\\p{Lower}*
关于java - 第一次使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15181519/