Regex Match all characters between two strings

后端 未结 14 1015
星月不相逢
星月不相逢 2020-11-21 07:42

Example: \"This is just\\na simple sentence\".

I want to match every character between \"This is\" and \"sentence\". Line breaks should be ignored. I can\'t figure o

14条回答
  •  悲&欢浪女
    2020-11-21 07:53

    RegEx to match everything between two strings using the Java approach.

    List results = new ArrayList<>(); //For storing results
    String example = "Code will save the world";
    

    Let's use Pattern and Matcher objects to use RegEx (.?)*.

    Pattern p = Pattern.compile("Code "(.*?)" world");   //java.util.regex.Pattern;
    Matcher m = p.matcher(example);                      //java.util.regex.Matcher;
    

    Since Matcher might contain more than one match, we need to loop over the results and store it.

    while(m.find()){   //Loop through all matches
       results.add(m.group()); //Get value and store in collection.
    }
    

    This example will contain only "will save the" word, but in the bigger text it will probably find more matches.

提交回复
热议问题