Java中用于匹配C 10 10或L 1 2 6 2或R 14 1 8 3的正则表达式

时间:2018-07-28 15:04:14

标签: java regex

我需要在Java中创建正则表达式的帮助,以将命令提示符下的输入仅与这四种格式中的任何一种匹配

bcc

C后面可以紧跟空格后的任意两个正整数,并且它们之间要有空格。 L&R后面可以有四个正整数,后跟空格,并且在它们之间有空格

除了这四个以外,我的应用程序均出现错误。 到目前为止,我已经实现了

C 10 10 
L 1 2 6 2 
R 14 1 8 3
Q

1 个答案:

答案 0 :(得分:4)

您可以使用以下正则表达式:

C(?:\s\d+){2}|[LR](?:\s\d+){4}|Q

描述:

C(?:\s\d+){2} - checks for literal character C followed by 2 digits
[LR](\s\d+){4} - checks for literal character L or R followed by 4 digits
Q - checks for character Q

演示:https://regex101.com/r/8Ro06s/2

输出:

Match 1
Full match  0-7 `C 10 10`
Match 2
Full match  9-18    `L 1 2 6 2`
Group 1.    16-18   ` 2`
Match 3
Full match  20-30   `R 14 1 8 3`
Group 1.    28-30   ` 3`
Match 4
Full match  31-32   `Q`

JShell输出:

jshell> Pattern patter = Pattern.compile("C(?:\\s\\d+){2}|[LR](\\s\\d+){4}|Q")
patter ==> C(?:\s\d+){2}|[LR](\s\d+){4}|Q
jshell> Matcher matcher = patter.matcher("C 10 10");
matcher ==> java.util.regex.Matcher[pattern=C(?:\s\d+){2}|[LR ... }|Q region=0,7 lastmatch=]
jshell> matcher.matches()
$9 ==> true
jshell> Matcher matcher = patter.matcher("L 1 2 6 2");
matcher ==> java.util.regex.Matcher[pattern=C(?:\s\d+){2}|[LR ... }|Q region=0,9 lastmatch=]
jshell> matcher.matches()
$11 ==> true
jshell> Matcher matcher = patter.matcher("R 14 1 8 3");
matcher ==> java.util.regex.Matcher[pattern=C(?:\s\d+){2}|[LR ... |Q region=0,10 lastmatch=]
jshell> matcher.matches()
$14 ==> true
jshell> Matcher matcher = patter.matcher("Q");
matcher ==> java.util.regex.Matcher[pattern=C(?:\s\d+){2}|[LR ... }|Q region=0,1 lastmatch=]
jshell> matcher.matches()
$15 ==> true