Search code examples
javaregexregular-language

How to use regular expressions in this case?


the String is:"LinksImagesListCodeHt1233ddmlImagesConsider112dd2Download",I want to get "ImagesConsider112dd2Download". so I used this expression "Images.*?Download".but it matches "ImagesListCodeHt1233ddmlImagesConsider112dd2Download".what's the correct expression should be?

Temporarily,there is a ugly way to solve this problem:

Pattern p = Pattern.compile(StringUtils.reverse("Download")+ ".*?" + StringUtils.reverse("Images") );
String s = "LinksImagesListCodeHt1233ddmlImagesConsider112dd2Download";
s = StringUtils.reverse(s);
Matcher m = p.matcher(s);
while (m.find()){
    m.end();
    System.out.println(StringUtils.reverse(m.group()));
}


Solution

  • To match the text between Images to Download which does not contain the word Images inside you can use negative lookaround like this

    Images((?!Images).)*Download
    

    Explanation
    Images -- Match literal string Images
    (?!Images). -- Match a character that does not follow Images word
    ((?!Images).)* -- Match zero or more times