Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 带有单独部分的字符串的正则表达式_Java_Regex - Fatal编程技术网

Java 带有单独部分的字符串的正则表达式

Java 带有单独部分的字符串的正则表达式,java,regex,Java,Regex,我不熟悉Java中的正则表达式,必须匹配 [0-9999][A-Z][0-9999][-][0-99]用于用户输入。我不太清楚如何区分不同的部分 您可以使用这个正则表达式[0-9]{1,4}[A-Z][0-9]{1,4}[-][0-9]{1,2}: public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter a St

我不熟悉Java中的正则表达式,必须匹配

[0-9999][A-Z][0-9999][-][0-99]
用于用户输入。我不太清楚如何区分不同的部分

您可以使用这个正则表达式
[0-9]{1,4}[A-Z][0-9]{1,4}[-][0-9]{1,2}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a String that match [0-9999][A-Z][0-9999][-][0-99]");

    String input = scan.nextLine();

    //If your input match with your String, then print Match, else Not match
    System.out.println(input.matches("[0-9]{1,4}[A-Z][0-9]{1,4}[-][0-9]{1,2}") ? 
            "Match" : "Not Match");
}
解释

[0-9]{1,4}      # A number between 0 and 9999
[A-Z]           # An alphabetic A to Z
[0-9]{1,4}      # A number between 0 and 9999
[-]             #  - 
[0-9]{1,2}      # A number between 0 and 99

您必须在正则表达式中使用组,如下所示

([0-9999])([A-Z])([0-9999])[-]([0-99])
然后您将能够使用查找组

你可以看到它在这里工作

你可以在


正则表达式模式如下所示:

 r'[0-9]{1,4}[A-Z][0-9]{1,4}-[0-9]{1,2}'
方括号定义集合,因此[0-9]将查找0到9之间的任何数字

大括号是量词,所以{1,4}匹配查找前面的1到4个匹配项

为了匹配破折号,我们只需键入字符


整个正则表达式将查找0到9之间的1到4个字符,然后是a到Z之间的一个字符,然后是0到9之间的1到4个字符,然后是一个破折号,然后是0到9之间的1到2个字符,好的,这与我的想法是一致的。非常感谢你!!这对你有帮助吗@MattyD?