Java Regex OR运算符无法正常运行

时间:2018-12-10 18:20:56

标签: java regex

我有这个字符串:

String test1=":test:block1:%a1%a2%a3%a4:block2:BL";

String test2=":test:block2:BL:block1:%a1%a2%a3%a4";

我创建了一个正则表达式模式以隔离此字符串

 block1:%a1%a2%a3%a4:

其余的字符串,让这些字符串像这样:

in the case of test1="block1:%a1%a2%a3%a4:"; (with ':' at the end)
in the case of test2=":block1:%a1%a2%a3%a4"; (with ':' at the beggining)

我创建的正则表达式是:

"(block1:(.*?):|:block1:(.*))";

使用test1可以正常工作,但是使用test2可以正常工作:

block1:%a1%a2%a3%a4:block2:BL";

有人可以帮我吗?

干杯!

1 个答案:

答案 0 :(得分:0)

您可以使用

block1:([^:]*)

它匹配block1:文本,然后将:以外的0个或更多字符捕获到组1中。

请参见Java demo

String patternString = "block1:([^:]*)";
String[] tests = {":test:block1:%a1%a2%a3%a4:block2:BL",
                  ":test:block2:BL:block1:%a1%a2%a3%a4"};
for (int i=0; i<tests.length; i++)
{
    Pattern p = Pattern.compile(patternString, Pattern.DOTALL);
    Matcher m = p.matcher(tests[i]);
    if(m.find())
    {
        System.out.println(tests[i] + " matched. Match: " +
                    m.group(0) + ", Group 1: " + m.group(1));
    }
}

输出:

:test:block1:%a1%a2%a3%a4:block2:BL matched. Match: block1:%a1%a2%a3%a4, Group 1: %a1%a2%a3%a4
:test:block2:BL:block1:%a1%a2%a3%a4 matched. Match: block1:%a1%a2%a3%a4, Group 1: %a1%a2%a3%a4