Pattern to extract text between parenthesis

后端 未结 3 2036
长情又很酷
长情又很酷 2020-12-01 10:47

How to extract string from \"(\" and \")\" using pattern matching or anything. For example if the text is `

\"Hello (Java)\"

3条回答
  •  独厮守ぢ
    2020-12-01 11:34

    List matchList = new ArrayList();
    Pattern regex = Pattern.compile("\\((.*?)\\)");
    Matcher regexMatcher = regex.matcher("Hello This is (Java) Not (.NET)");
    
    while (regexMatcher.find()) {//Finds Matching Pattern in String
       matchList.add(regexMatcher.group(1));//Fetching Group from String
    }
    
    for(String str:matchList) {
       System.out.println(str);
    }
    

    OUTPUT

    Java
    .NET
    

    What does \\((.+?)\\) mean?

    This regular Expression pattern will start from \\( which will match ( as it is reserved in regExp so we need escape this character,same thing for \\) and (.*?) will match any character zero or more time anything moreover in () considered as Group which we are finding.

提交回复
热议问题