1

the below will give me between _ and . for example Pet_you.txt will give me you

but if I get pet_te_you.txt will get te_you but instead I need you result. how to fix my pattern to take last _?

Pattern MY_PATTERN = Pattern.compile("\\_(.*?)\\.");
Matcher m = MY_PATTERN.matcher("pet_te_you.txt");
while (m.find()) {
    Type = m.group(1);
    System.out.println(dbType);
}
CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
Moudiz
  • 7,211
  • 22
  • 78
  • 156

4 Answers4

2

You just have to avoid "_" in the capture pattern.

Pattern.compile("\\_([^_]+?)\\.")
Dennis C
  • 24,511
  • 12
  • 71
  • 99
2

As a non-regex pattern, you could use substring twice - once for the lastIndexOf("_") and then for the lastIndexOf(".").

s = s.substring(s.lastIndexOf("_") + 1);
s = s.substring(0, s.lastIndexOf("."));

Or a fun alternative to combine them both in a *non-ugly way:

s = s.substring(s.lastIndexOf("_") + 1).substring(0, s.substring(s.lastIndexOf("_") + 1).lastIndexOf("."));

Or perhaps, loop through the String in reverse (I used a StringBuilder), from lastIndexOf(".") - 1 until you reach a non-character (or perhaps a _).

for (int i = s.lastIndexOf(".") - 1; i > 0; i--) {
    if (Character.isAlphabetic(s.charAt(i))) {
        sb.append(s.charAt(i));
    } else {
        break;
    }
}

Here's an online example.

*This is definitely ugly

achAmháin
  • 4,176
  • 4
  • 17
  • 40
1

Same implementation using lastIndexOf

String text = "pet_te_you.txt";
System.out.println(text.substring(text.lastIndexOf("_")+1, text.lastIndexOf(".")));
Anirudh
  • 437
  • 2
  • 10
1

you can match with look around: (?<=_)[^_]+(?=\.), and yes, you can have result using lastIndexOf too.

String as[] = {"pet_te_you.txt", "Pet_you.txt"};
Pattern p =  Pattern.compile("(?<=_)[^_]+(?=\\.)");
for (String s : as) {
    int beginIndex = s.lastIndexOf("_");
    int endIndex = s.lastIndexOf(".");
    if (beginIndex >= 0 && endIndex >= 0 && beginIndex < endIndex) {
        System.out.println(s.substring(beginIndex + 1, endIndex));
    }

    Matcher m = p.matcher(s);
    if (m.find()) {
        System.out.println(m.group());
    }
}

output:
    you
    you
    you
    you
Shen Yudong
  • 1,190
  • 7
  • 14