gpt4 book ai didi

大写字母的 Java 正则表达式

转载 作者:行者123 更新时间:2023-12-05 09:23:07 37 4
gpt4 key购买 nike

我开始熟悉 Java,但我仍然觉得正则表达式很困惑。我需要检查一个元素是否连续有两个大写字母,连续三个大写字母,连续四个大写字母,或者一个大写字母,一个空格,然后是另一个大写字母。这是我到目前为止的代码,但我觉得有更好(也更有效)的方法来做到这一点。

 public class First {
public static void main(String[] args) {
String one = "A scenario - CAPI 200 - 001";
String two = "A scenario - C T 200 - 001";
String three = "A scenaRio - CT 200 - 001";
String four = "A sCenario - CAP 200 - 001";


Pattern p = Pattern.compile("[A-Z][A-Z][A-Z][A-Z]");
Pattern q = Pattern.compile("[A-Z] [A-Z]");
Pattern r = Pattern.compile("[A-Z][A-Z]");
Pattern s = Pattern.compile("[A-Z][A-Z][A-Z]");

Matcher m =p.matcher(one);
if (m.find()){
System.out.println(m.group());
}
Matcher d =q.matcher(two);
if (d.find()){
System.out.println(d.group());
}
Matcher e =r.matcher(three);
if (e.find()){
System.out.println(e.group());
}
Matcher a =s.matcher(four);
if (a.find()){
System.out.println(a.group());
}
}
}

如有任何帮助,我们将不胜感激。

最佳答案

用这个来匹配2-4个大写字母,或者大写,空格,大写

([A-Z]{2,4})|([A-Z] [A-Z]) 

编辑:刚刚意识到您可能需要区分匹配的组。

在这种情况下,您所做的并没有错,但可以使用 [A-Z]{2} 方法进行优化以缩短正则表达式。如果您告诉我们代码需要做什么,我们可以更好地提出满足您需求的解决方案。

关于大写字母的 Java 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24186561/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com