In Java regular expressions are used to extract the contents inside of of

  • 2020-04-01 01:39:43
  • OfStack

Yesterday, I encountered a small problem and needed to deal with some users in batches. The format of the user sent from the foreground is as follows, and the content in the middle of the brackets should be extracted (without brackets).

Teachers' 10 (0010).
Teachers, 11 (0011).
Teachers 9 (009)
Teachers' 12 (0012).
Teachers' 13 (0013).
Teachers 14 (0014).

I wanted to do it with string.split () and substring() in Java, but I had to do it multiple times, so I used regular expressions. Although the syntax is pretty much forgotten, it's easier to use assertions in your memory (the key is to want the result to be unbraced). Open RegexBuddy and try it out. It's easy:
< img Alt = "" border = 0 SRC =" / / img.jbzj.com/file_images/article/201304/201304140001.jpg ">
The following is the Java implementation code:


public List<String> getTeacherList(String managers){
        List<String> ls=new ArrayList<String>();
        Pattern pattern = Pattern.compile("(?<=\()(.+?)(?=\))");
        Matcher matcher = pattern.matcher(managers);
        while(matcher.find())
            ls.add(matcher.group());
        return ls;
    }

Finally, the zero-width assertion used is attached:

Broad assertion (? = exp) Matches the position in front of the exp (? < = exp) Matches the position after the exp (? ! Exp) Matches a position that is not followed by an exp (? < ! Exp) Matches the previous position that is not exp
 


Related articles: