Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.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_String - Fatal编程技术网

如何在Java中提取子字符串

如何在Java中提取子字符串,java,regex,string,Java,Regex,String,我有一根绳子 when (update [page1] [desc]) and match ([desc] is not null), then (Rule:setvalue; SourceValue:[ign [desc]]; TargetField:[desc2]) 有没有人有好的方法来提取3个字符串: (update [page1] [desc]) ([desc] is not null) (Rule:setvalue; SourceValue:[ign [desc]]; TargetF

我有一根绳子

when (update [page1] [desc]) and match ([desc] is not null), then (Rule:setvalue; SourceValue:[ign [desc]]; TargetField:[desc2])
有没有人有好的方法来提取3个字符串:

(update [page1] [desc])
([desc] is not null)
(Rule:setvalue; SourceValue:[ign [desc]]; TargetField:[desc2])
3部分可以是任何字符。Java正则表达式也可以很好地实现。但添加关键字“when”,“and match”,“then”可能会使场景更加逼真

public static void main(String[] args) {
        String str = "when (update [page1] [desc]) and match ([desc] is not null), then (Rule:setvalue; SourceValue:[ign [desc]]; TargetField:[desc2])";
        Pattern pattern = Pattern.compile("\\((.+?)\\)");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }

    }
输出:

(update [page1] [desc])
([desc] is not null)
(Rule:setvalue; SourceValue:[ign [desc]]; TargetField:[desc2])
如果输出中不需要大括号:

更改:

System.out.println(matcher.group());
致:


您可以尝试以下模式:

String regex = "\\([^)]++\\)";

圆括号也可以嵌套吗?是的,圆括号可以嵌套只要写一个循环来跟踪开始括号的数量。@C.C:
你希望(快速(棕色)(狐狸跳过)懒惰的)狗有什么输出呢?我们没有这种语句,格式是when(某物)和match(某物),然后(某物),某物可能包含任何字符,包括圆括号正则表达式有点多余:
“\\(.+?\\)”
就足够了。但请注意,它将在一次匹配中匹配
()(文本)
。圆括号可能是嵌套的,因此()可能没有太多意义,可以使用关键字“when”,“and match”,“then”来匹配它?
String regex = "\\([^)]++\\)";